c programming - can't get desired output - c

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.

Related

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 is my code not reversing a two digit number?

I am trying to reverse a two digit number, and I understand there may be better ways of doing this, but I am curious now why the way I chose does not work.
If I input 48, it produces 84 (a successful reversal).
If I input 84, it produces 38. If I input 47, it produces 64. These are just some examples of unsuccessful reversals.
int digit_one, digit_two, input;
float a, b;
printf("Enter a two-digit number: ");
scanf("%d", &input);
a = input * 0.1; // turns the two digit input figure into a float with a digit after the decimal point
digit_one = a; // turns the float into an integer, eliminating the digit after the decimal point
b = a - digit_one; // produces a float that has a 0 before the decimal point, and a digit after the decimal point
digit_two = b * 10; // moves the digit that was after the decimal point, to before the decimal point
printf("The reversal is: %d%d\n", digit_two, digit_one);
Thank you!
a - digit_one is a fractional number. If it's slightly less than the exact result (because for example 0.7 cannot be represented exactly as a float), then (a - digit_one) * 10 will be slightly less than the desired integer, and so digit_two will be one less than you expect.
You can avoid floating point, and write int digit_one, digit_two = input / 10, input % 10;
Working with floats is not the best approach here. With the input "84", b * 10 = 3.999996 which is 3 when you convert it to an integer.
This is a classic computer science problem with floats. Here are some links where this has been explained very well:
Is floating point math broken?
https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Your problem can be solved differently:
int digit_one, digit_two, input, a, b;
printf("Enter a two-digit number: ");
scanf("%d", &input);
digit_one = input % 10;
digit_two = (input / 10) % 10;
printf("The reversal is: %d%d\n", digit_one, digit_two);
int result =0;
do{
result = (result * 10) + (input % 10);
input /= 10;
} while(input)
printf("The reversal is: %d\n", result);
You can print the 'result' variable to get any integer value irrespective of 2 digit or 3 digit

Result is being rounded up [C] [duplicate]

This question already has answers here:
C program to convert Fahrenheit to Celsius always prints zero
(6 answers)
Closed 7 years ago.
I've been writing this program in C, and I've noticed that the division result, captured in the fee variable, has always fixed value, and that is 5.00, but the result should be 5.78.
Can you explain why it has this behaviour and what should I do to fix it
?
#include <stdio.h>
#include <stdlib.h>
int main(void){
printf("Input package dimensions: width, heigth, length \n");
int width, height, length;
scanf("%d", &width );
scanf("%d", &height );
scanf("%d", &length );
int weight = width*height*length;
printf("%d\n", weight);
float fee = weight/166;
printf("%.2f\n", fee);
printf("The fee is : $%.2f\n and", fee);
system("pause");
return 0;
}
Both weight and 166 have type int, therefore weight/166 is an integer division, which truncates any fractional part. The fact that you assign the result to a variable of type float is irrelevant.
You want to instead perform floating-point division, which you can accomplish by ensuring that at least one of the operands has a floating-point type. One of the simplest ways to do that would be
float fee = weight / 166.0;
Thats because you are dividing int by int. To get a floating point number at least one of them should be a floating number.
float fee = weight/166.0;
Try:
float fee = (float)weight/166.0;
Otherwise an integer-division is performed and then casted to float.
float fee = weight/166;
166 is int and wight is int. int divided by another int will always result in int and only when the result is stored in fee, it is casted to float.
You can fix it by
float fee = (float)weight/166;
or by
float fee = weight/166.0;
In this line weight and 166 will be divided as integers and then cast to float.
float fee = weight/166; // integer division
You need to cast or define one of them as float for a more accurate division.E.g.
float fee = weight/166.0; // double precision division
Or
float fee = (float) weight/166; // single precision division (float)
Or if you want to surprise your colleagues :
float fee = weight/166.0f; // single precision division (float)
That's because dividing an integer by an integer results in an integer, And that's what weight/166 does. It is later covered to a floating point, but that's "too late".
The most explicit way to have a floating point division in your case is:
(float)weight / 166.0f
This should fix it.
float fee = weight/166.0;

C program to round numbers, rounded to second position after the decimal place [duplicate]

This question already has answers here:
How do I restrict a float value to only two places after the decimal point in C?
(17 answers)
Closed 8 years ago.
I am writing a simple program to round numbers. It works fine when I enter something like 1.4 (gives me 1.0) or 2.6 (gives me 3.0). But when I enter 1.45, it should give me 1.5 but it prints 1.0. Or for 2.85 (should be 2.9, it prints 3.0). How do I make this work? I cannot use any functions.
#include<stdio.h>
const float add = 0.5;
int main(void)
{
float v;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
v = v + add;
v = (int)v;
printf("The rounded value is %.2f", v);
return 0;
}
Try this code. You need to break your floating value into Modulus and Dividend.
#include<stdio.h>
int main(void)
{
float v;
int con, r_value, mul;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
mul=v*10;
con=mul%10;
r_value=mul/10;
if(con>=5)
r_value=r_value+1;
else
r_value=r_value;
printf("The rounded value is %.2d", r_value);
return 0;
}
Above code is modified to be used for Negative Numbers also.
float v;
int con, r_value, mul;
printf("Please enter a value to be rounded: ");
scanf("%f", &v);
mul=v*10;
con=mul%10;
r_value=mul/10;
if(v>0)
{
if(con>=5)
r_value=r_value+1;
else
r_value=r_value;
}
else if (v<0)
{
if(con<=-5)
r_value=r_value-1;
else
r_value=r_value;
}
printf("The rounded value is %.2d", r_value);
Int value simply removes the value after decimal point it does't round of to nearest number
In your case when you give 2.45
2.45 + 0.5 = 2.95
which is rounded off to 2(2.0 since your asking for precision) i.e the decimal part is truncated not rounded off.
Ints do not have decimal places, so a cast from float to int then back to float will leave only the integer value.
Your subject (rounding to the second decimal place) does not match your question (rounding to an arbitrary position based on the input). That makes it difficult to answer your question properly.
That said, your code
v = v + 0.5;
v = (int)v;
will round a number to the nearest integer. I'm not sure why you expect the int cast to do anything else.
You are using v = (int)v;, how can it give 1.5 for input of 1.45.
To get what you want, you can just print the decimal digits 1 less than in original, i.e.
Suppose you have 2.455 which has 3 decimal digits, you can just print that number using %.2f and it will automatically be rounded off.
You can do:
printf("%.2f", ((int)(v * 100 + 0.5) / 100.0));

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