C program not giving the correct output - c

#include<stdio.h>
main()
{
int m1, m2, m3, m4, m5, per;
printf("Enter marks in five subjects");
scanf("%d %d %d %d %d", &m1, &m2, &m3, &m4, &m5);
per=(m1+m2+m3+m4+m5)/500*100;
if(per>=60)
printf("First division");
else if(per>=50)
printf("Second division");
else if(per>=40)
printf("Third division");
else
printf("Fail");
}
Enter marks in five subjects 100, 100, 10, 50, 60
After giving this input printf showing Fail. But it will be First Division.
What is the problem in this program?

You are performing integer division
per=(m1+m2+m3+m4+m5)/500*100;
change it to
per = ((float)(m1 + m2 + m3 + m4 + m5)) / 500 * 100;
and since the maximum value of each mn is 100 so the maximum value of their sum is 500, if it's less than 500 integer division yields always 0.

Iharob is right - the problem is in making integer division (i.e. int_operator / int_operator), and only after that multiplication works.
Modifications of Iharob’s solution can be also:
per = (m1 + m2 + m3 + m4 + m5) / 500.0 * 100; // now 500.0 is of double type
But assigning float (or double) values to integer variables is not always good idea because int has smaller range. So it is better to optimize your expression, e.g.:
per=(m1+m2+m3+m4+m5)/5;
Also you can change type of per to float (or double), or decide what you want from the result (rounding / separation integer part from remainder / just integer part)

Related

Calculator for pi stopping

I'm trying to calculate pi with the precision of 10 decimal places. And the efficiency has to be the best(speed and memory allocation). The programming language is C in CodeBlocks.
I don't want to change the formula I'm using:
Problem: after a while, the resulting number stops incrementing but the iteration doesn't stop.
I'm not sure if this is a math problem or some kind of variable overflow.
The resulting number is 3.1415926431 and the number I want to achieve is 3.1415926535.
Every time the incrementation stops at this specific number and the iteration continues. Is there a possibility of an overflow or something?
Now I'm printing out every thousandth iteration (just the see the process) This will be deleted in the end.
notice the
a = n; a *= 4 * a; is for memory efficiency, there are more similar cuts I did.
code I'm using
#include <stdio.h>
#include <math.h>
#include <time.h>
int main(){
double time_spent = 0.0;
clock_t begin = clock();
int n=1;
double resultNumber= 1;
double pi = 3.1415926535;
double pi2 = pi / 2;
double a;
while(1){
a = n;
a *= 4 * a;
resultNumber *= a / (a - 1);
n++;
if (fabs(resultNumber - pi2) < pow(10,-10))
break;
if (n%1000==0) {
printf("%.10f %d\n", resultNumber*2, n);
}
}
clock_t end = clock();
time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
printf("The elapsed time is %f seconds", time_spent);
return 0;
}
You can try it out here:
https://onlinegdb.com/q2Gil1DHdy
Is there a possibility of an overflow or something?
The precision of floating-point numbers is limited. In a typical C implementation, double has 53 bits of mantissa, which corresponds to about 15 significant decimal digits. But the range of such FP numbers is much larger than +/- 1015, so when your FP number is large enough, the units digit is not significant. Then subtracting 1 from it will not produce a different number. When your a reaches that point, the quotient a / (a - 1) will be identically 1, so multiplying by that will not change the working result.
It's possible that you would get enough additional precision by using long double instead of double. That might help both in getting you more terms in your product before the problem described above sets in, and also by reducing the relative magnitude of FP rounding errors earlier in the computation.
You can rescue a little of the accuracy by the following trick:
4n² / (4n² - 1) = 1 + 1 / (4n² - 1)
For large n, these factors are close to 1 and challenge the floating-point representation. You can use the identity
(1 + a)(1 + b)(1 + c)... = 1 + (a + b + c...) + (ab + ac + ... + bc + ...) ...
So for small terms a, b, c... (when the second order terms disappear), it is more accurate to use the approximation 1 + (a + b + c...), of course summing inside the parenthesis first.

Why is my program to calculate Mean square error not giving any output?

So I have this question in statistics that I need to solve using C programming. We have to calculate the values of MSE for various values of theta(population parameter of exponential distribution) and n(sample size. We set theta as constant and calculate MSE for various values of n, and then make n constant and calculate MSE for various theta.
Then we tabulate the results.
This is my program
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
int main(void)
{
int n ,N=5;
float theta,msum =0.0,mse; //paramters
int i,j; // loop
printf("Enter the value of n ");
scanf("%d", &n);
printf("Enter the value of theta ");
scanf("%f ", &theta);
//float u[n], x[n];
//first we fix theta and find MSE for different values of n
for(i=0;i<N;i++)
{
float sum = 0.0;
for(j=0;j<n;j++)
{
//x[j] = (-1/theta)*log(1-(rand()/RAND_MAX));
sum += (-1/theta)*log(1-(rand()/RAND_MAX)); //generates random number from unifrom dist and then converts it to exponential using inverse cdf function
printf("%d%d", i, j);
}
float thetahat = n/sum;
msum += (thetahat - theta)*(thetahat - theta);
}
mse = msum/N;
printf("The MSE with n=%d and theta=%f is %f", n, theta, mse);
return 0;
}
However, this program is not giving any output. I tried multiple IDEs.
Error count is zero. What am I doing wrong?
Use floating point division
rand()/RAND_MAX is int division with a quotient of 0 or 1. Uses 1.0 * rand() / RAND_MAX to coax a floating point division.
Avoid log(0)
log(1-(rand()/RAND_MAX) risks log(0), even with 1.0 * rand() / RAND_MAX. I suspect log(1.0 * (RAND_MAX + 1LL - rand()) / (RAND_MAX + 1LL) will achieve your goal.
Why the space?
The trailing space in scanf("%f ", &theta) obliges scanf() to not return until non-white-space inputs occurs after the number. Drop the space and check the return value.
if (scanf("%f", &theta) != 1) {
; // Handle bad input
}
double vs. float
Code curiously uses float objects, yet double function calls.
Use double as the default floating point type in C unless you have a compelling need for float.

Why does pow() subtract 1 from my result? [duplicate]

This question already has answers here:
return value of pow() gets rounded down if assigned to an integer
(4 answers)
Closed 5 years ago.
I'm new with C programming, and I've written this code as I've been asked to do something using mainly printf() and scanf(). I know there could be better ways to handle this, which I'll need to learn soon, but anyways, for now this is what I have:
int add1, add2, exponent, exponent_result, multiplier, parenthese, product, sub, total;
printf("Let's try a slightly more complex calculation, in which we'll use an exponent.\n\n");
printf("Type 5 whole numbers or integers.\n\n");
scanf("%i %i %i %i %i", &add1, &add2, &exponent, &multiplier, &sub);
printf("Out of the numbers you typed, we're going to make this operation: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);
exponent_result = pow(add2, exponent);
parenthese = add1 + exponent_result;
product = parenthese * multiplier;
total = (add1 + exponent_result) * multiplier - sub;
printf("Per PEMDAS, the correct order of operation is Parentheses, then Exponents, then Multiplications and Divisions, and finally Additions and Subtractions.\n\n");
printf("Therefore: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub);
printf("...is equal to: (%i + %i) * %i - %i\n\n", add1, exponent_result, multiplier, sub);
printf("...is equal to: %i * %i - %i\n\n", parenthese, multiplier, sub);
printf("...is equal to: %i - %i\n\n", product, sub);
printf("...is equal to: %i", total);
If you run this code, you'll realize that the output for exponent_result, which is calculated using the pow() function, always has 1 subtracted from it. For instance, if exponent_result is supposed to be the result of 5^3, the result for that will be 124 instead of 125.
What am I doing wrong?
Fyi, I have this at the beginning of my file.
#include <stdio.h>
#include <math.h>
pow is evaluated in floating point arithmetic, and is probably implemented as pow(x, y) = exp(y * log(x)).
This can cause the result to "go off": you probably get a value just shy of 125, which is truncated to 124 when the double return type from pow is converted back to an int.
The simplest remedy is to build your own pow function for integral arguments. See The most efficient way to implement an integer based power function pow(int, int)

c programming - can't get desired output

char choice, y, n;
float percentage;
int marks;
printf("Do you want to know your percentage?(y/n):\n\n");
scanf(" %c", &choice);
if (choice == 'y') {
printf("Enter Your 2nd Sem Marks:\n\n");
scanf(" %d", &marks);
percentage = (marks / 775) * 100;
printf("Your 2nd Sem Percentage is %.2f", percentage);
} else
printf("Thankyou!!!!\n\n\n");
I can't calculate the percentage using the above code - I get output 0.00...
For example when i give input as 536,instead of showing result as 69.16,it shows 0.00
please help me out
Since marks is an int and will always be less than 775, the expression (marks / 775), after integer division, will always yield zero. You should cast to a floating point number in the expression, or otherwise have a floating point number in the expression, to preserve the remainder of the division.
This is because you are doing this
percentage = (marks/775) * 100;
You should instead do this
percentage = ((float)marks/775) * 100;
Remember that (marks/775) will give an integer as both the operands are integers.
Int his case, 536/775 will be 0 as per integer division.
You should instead be performing float division for getting the percentage.

Why does this integer division yield 0?

Could someone tell me why the following code is outputting 0 at the marked line?
It seems as if everything is correct but then when I try to get the result near the end it's giving me 0 each time.
#include <stdio.h>
int main() {
// Gather time-lapse variables
int frameRate, totalLengthSecs;
printf("How many frames per second: ");
scanf("%i", &frameRate);
printf("--> %i frames confirmed.", frameRate);
printf("\nDesired length of time-lapse [secs]: ");
scanf("%i", &totalLengthSecs);
printf("--> %i seconds confirmed.", totalLengthSecs);
int totalFrames = frameRate * totalLengthSecs;
printf("\nYou need %i frames.", totalFrames);
// Time-lapse interval calculation
int timeLapseInterval = totalLengthSecs / totalFrames;
printf("\n\n%i", timeLapseInterval); // <-- this prints 0
return 0;
}
In short: Integer division truncates
You need the following:
double timeLapseInterval = (double) totalLengthSecs / (double)totalFrames;
printf("\ntimeLapseInterval : %f \n", timeLapseInterval);
You are performing integer math.
Math between two integers will produce an integer. And the result will be rounded towards zero.
This line:
totalLengthSecs / totalFrames;
Is likely producing a result that's between 0 and 1. And getting rounded to 0
You are printing integers and therefore it will round down the value.
timeLapseInterval / totalFrames will be (1 / frameRate) which will be < 1 unless frameRate is 1 (or 0 in which case you have an error dividing by 0)
When you divide 2 numbers in C and the denominator is integer, the compiler intends it as an integer division. Therefore, if you divide 1 divided 2, it returns zero and not 0.5
Moreover, your output variable is an integer too, hence, if you expect decimal outputs, you won't get it.
You can fix it by doing:
float timeLapseInterval = totalLengthSecs / (float)totalFrames;
printf("\n\n%f", timeLapseInterval);
I hope this helps

Resources