Result is being rounded up [C] [duplicate] - c

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;

Related

Round float to 2 decimal places in C language?

float number = 123.8798831;
number=(floorf((number + number * 0.1) * 100.0)) / 100.0;
printf("number = %f",number);
I want to get number = 136.25
But the compiler shows me number = 136.259995
I know that I can write like this printf("number = %.2f",number) ,but I need the number itself for further operation.It is necessary that the number be stored in a variable as number = 136.25
It is necessary that the number be stored in a variable as number = 136.25
But that would be the incorrect result. The precise result of number + number * 0.1 is 136.26787141. When you round that downwards to 2 decimal places, the number that you would get is 136.26, and not 136.25.
However, there is no way to store 136.26 in a float because it simply isn't a representable value (on your system). Best you can get is a value that is very close to it. You have successfully produced a floating point number that is very close to 136.26. If you cannot accept the slight error in the value, then you shouldn't be using finite precision floating point arithmetic.
If you wish to print the value of a floating point number up to limited number of decimals, you must understand that not all values can be represented by floating point numbers, and that you must use %.2f to get desired output.
Round float to 2 decimal places in C language?
Just like you did:
multiply with 100
round
divide by 100
I agree with the other comments/answers that using floating point numbers for money is usually not a good idea, not all numbers can be stored exactly. Basically, when you use floating point numbers, you sacrifice exactness for being able to storage very large and very small numbers and being able to store decimals. You don't want to sacrifice exactness when dealing with real money, but I think this is a student project, and no actual money is being calculated, so I wrote the small program to show one way of doing this.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
double number, percent_interest, interest, result, rounded_result;
number = 123.8798831;
percent_interest = 0.1;
interest = (number * percent_interest)/100; //Calculate interest of interest_rate percent.
result = number + interest;
rounded_result = floor(result * 100) / 100;
printf("number=%f, percent_interest=%f, interest=%f, result=%f, rounded_result=%f\n", number, percent_interest, interest, result, rounded_result);
return EXIT_SUCCESS;
}
As you can see, I use double instead float, because double has more precession and floating point constants are of type double not float. The code in your question should give you a warning because in
float number = 123.8798831;
123.8798831 is of type double and has to be converted to float (possibly losing precession in the process).
You should also notice that my program calculates interest at .1% (like you say you want to do) unlike the code in your question which calculates interest at 10%. Your code multiplies by 0.1 which is 10/100 or 10%.
Here is an example of a function you can use for rounding to x number of decimals.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stddef.h>
double dround(double number, int dp)
{
int charsNeeded = 1 + snprintf(NULL, 0, "%.*f", dp, number);
char *buffer = malloc(charsNeeded);
snprintf(buffer, charsNeeded, "%.*f", dp, number);
double result = atof(buffer);
free(buffer);
return result;
}
int main()
{
float number = 37.777779;
number = dround(number,2);
printf("Number is %f\n",number);
return 0;
}

Double variable doesn't return the right values of a division [duplicate]

This question already has answers here:
Why dividing two integers doesn't get a float? [duplicate]
(7 answers)
Closed 5 years ago.
input example : 356
356/100, is suppused to be 3.56
But I'm getting 3.0000000000, I'm using ideone online compiler for C.
#include <stdio.h>
#include <math.h>
int main() {
int n;
double frac;
scanf("%d", &n);
frac = (n/100);
printf("%lf", frac);
return 0;
}
That's because here frac = (n/100); you are doing plain integer arithmetic (as n is declared as an int and 100 is interpreted as an int (any whole number is taken to be an int unless specified otherwise)). What you need to do is say explicitly that you want to do an arithmetic operation with digits after decimal point. One way is to use a cast: frac = ((double) n/100);
If you don't use the cast, the division will be performed as you expect, but then the digits after the decimal point will be dropped. Since frac is declared as a double, 0s would get tacked on to the end.
In C, the result of division of two integer numbers (e.g. int, short, long) is also an integer (it is counter-intuitive, but it is implemented this way for performance reasons). As a result, the result of 5/2 is 2 and not 2.5. This rule is only for integer numbers. So, if you need to get a floating-point result, at least one of the numbers in a division operation must be of a floating-point type.
In case of your code, if you use 100.0 instead of 100, you will get the desired result. Also you can use casts or define n as double.
This should work:
#include <stdio.h>
#include <math.h>
int main() {
int n; // You can define n as double but don't forget to modify scanf accordingly.
double frac;
scanf("%d", &n);
frac = (n/((double)100)); // Or, frac = (n/100.0)
printf("%lf", frac);
return 0;
}
You cannot call division using integers to be double without declaring it.
For example
int / int will result int.
Try declaring n as double
double n;
scanf("%lf", &n);
frag = n/100;
input data type is an integer.
just change it to double or float to fix this problem.
int main() {
double n;
double frac;
scanf("%d", &n);
frac = (n/100);
printf("%lf", frac);
return 0;
}

Why doesn't roundf() round a float value and why do int - float math operations return wrong values?

I don't understand why doesn't the roundf() function from math.h round the donation variable, whilst it rounds livestockPM without a problem. I need to use the rounded values for other calculations, but I'm using printf to check if the values are correct, and it simply returns wrong values (doesn't round variable donation). Also, the variable final only returns values as if rounded to .00, doesn't matter what variables farmer1,2,3 hold.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int farmer1 = 9940;
int farmer2 = 4241;
int farmer3 = 7779;
float livestockPM = (float)farmer1 / (float)farmer2;
printf("livestock: %f\n",livestockPM);
livestockPM = roundf(livestockPM * 100) / 100;
printf("livestock rounded: %f\n",livestockPM);
float donation = (float)livestockPM * (float)farmer3;
printf("donation: %f\n", donation);
donation = roundf(donation * 100.00) / 100.00;
printf("donation rounded: %f\n", donation);
float final = donation * (float)farmer2;
printf("final: %f\n", final);
return 0;
}
Output:
livestock: 2.343787
livestock rounded: 2.340000
donation: 18202.859375
donation rounded: 18202.859375
final: 77198328.000000
Anyone got any idea why? I was thinking because of multiplying float with int, but I can't seem to get it work like this. I've tried removing the (float) from integer variables, but the results were undesirable as well. Thanks.
OP's float is encoded using binary floating point and 18202.859375 lacks precision to take on a value that "%f" prints as 18202.860000.
A float cannot represent every possible number. As a binary floating point number it can represent numbers like below. See IEEE 754 Converter, but not in between.
18202.859375
18202.86138125
When the following executes, the best possible result is again 18202.859375.
float donation_rounded = roundf(18202.859375 * 100.00) / 100.00;
Recall that printf("%f\n", x) prints a number rounded textually to the closest 0.000001 value.
Code could use double, but the same problem will occur with very large numbers, but may meet OP''s immediate need. #user3386109
As OP appears to be trying to cope with money, there is no great solution in standard C. best money/currency representation goes into some of the issues.

C print issue, Decimals equating to 0

Im essentially brand new to C, so bear with me. So basically i have to create a program to calculate the amount of dough per sqft. After rechecking my math and debugging for a very long time; ive found that sradius/INCHES_PER_FEET is coming out to 0.
INCHES_PER_FEET = 12. Now the issue is if i input any value equal to or greater than 12 for the radius, the function will work properly; but if i input 8, and 8/12 is less than 1 a decimal, the program will automatically equate it to 0 and im not sure how i can fix that. Insight would be really appreciated.
int main(){
//define radius variables
int sradius;
printf("What is the radius of your small pizza, in inches?\n");
scanf("%d", &sradius);
int mradius;
printf("What is the radius of your medium pizza, in inches?\n");
scanf("%d", &mradius);
int lradius;
printf("What is the radius of your large pizza, in inches?\n");
scanf("%d", &lradius);
//define pizzas sold variables
int spizzas;
printf("How many small pizzas do you expect to sell this week?\n");
scanf("%d", &spizzas);
int mpizzas;
printf("How many medium pizzas do you expect to sell this week?\n");
scanf("%d", &mpizzas);
int lpizzas;
printf("How many large pizzas do you expect to sell this week?\n");
scanf("%d", &lpizzas);
//dough calculation per size
double sdough,mdough,ldough;
sdough = (PI*((sradius/INCHES_PER_FEET)*(sradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
mdough = (PI*((mradius/INCHES_PER_FEET)*(mradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
ldough = (PI*((lradius/INCHES_PER_FEET)*(lradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
//final amount of dough
double fdough;
fdough = ((sdough*spizzas)+(mdough*mpizzas)+(ldough*lpizzas));
//print statement
printf("you need to order %.3f " ,fdough);
return 0;
}
Cast all the radius into a double before calculating and you will get a double as the result like this:
double sdough,mdough,ldough;
sdough = (PI*(((double)sradius/INCHES_PER_FEET)*((double)sradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
mdough = (PI*(((double)mradius/INCHES_PER_FEET)*((double)mradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
ldough = (PI*(((double)lradius/INCHES_PER_FEET)*((double)lradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
C typically allows you to do operations on a single "data-type". However, if you try to do such operations, C has some preset defaults. For example, in the following code, C will assign the value of a as 0.0000 and not 0.6666, even though you have declared a as float:
int main(void)
{
float a;
int b=2, c=3;
a=b/c;
printf("%f",a);
return 0;
}
This happens because b and c are declared integers. You use type-casting in such cases, i.e., force-changing the declared data-type. The above code will give you desired output if you do the following:
int main(void)
{
float a;
int b=2, c= 3;
a=(float)b/(float)c;
printf("%f",a);
return 0;
}
The answer answered by #cool-guy depicts the same, in your specific case.
The excessive use (IMNSHO) of parentheses is forcing the division to be integer. If you had written
x = PI * sradius / INCHES_PER_FEET * sradius / INCHES_PER_FEET * DOUGH_PER_SQFT;
instead of
x = (PI*((sradius/INCHES_PER_FEET)*(sradius/INCHES_PER_FEET))*DOUGH_PER_SQFT);
the divisions would have been done in floating point and you would get a more accurate value. Assigning that float value to an int causes truncation instead of rounding, so the accuracy could be improved by adding a half:
x = PI * sradius / INCHES_PER_FEET * sradius / INCHES_PER_FEET * DOUGH_PER_SQFT + 0.5;
Most compilers will complain about the implicit conversion to int if warning diagnostics are sufficiently enabled.
The other answers are correct in that forcing type conversion with a typecast will also get an accurate result. Or you could simply define the denominator as a float constant:
const float INCHES_PER_FEET = 12.0;
This requires each division to be done in floating point even though the numerator is an int.

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));

Resources