[SOLVED]
I'm learning C and I encountered some problems during my learning process.
When I'm trying to calculate an int datatype and float datatype in one equation, I ended up getting 2 different outputs. and I'm confused because logically the result should be the same.
here is my code version 1 and version 2. The difference lies in the variable z.
- the first case: the value of z is 1
- the second case: the value of z is 0
All the input is 11
UPDATE 1
thank you all for your comments and answers. but I'm still confused about what role the variable p
plays in case 1 and how could it led to the variable z
to be 1 rather than 0?
Case 1
int main()
{
float a, fee, p;
int x, y,z;
scanf("%f", &a);
fee = 0.6 * a;
x = (int)(fee);
y = (int)(2 * fee - 2 * x);
p = fee * 10.0;
z = (int)(p - 10 * x - 5 * y);
printf("%f %d %d %d", fee, x, y, z);
return 0;
}
Case 2
int main()
{
float a, fee, p;
int x, y,z;
scanf("%f", &a);
fee = 0.6 * a;
x = (int)(fee);
y = (int)(2 * fee - 2 * x);
z = (int)(fee * 10.0 - 10 * x - 5 * y);
printf("%f %d %d %d", fee, x, y, z);
return 0;
}
CodePudding user response:
1) z = (int)(p - 10 * x - 5 * y);
F I I I I // Float or Int
2) z = (int)(fee * 10.0 - 10 * x - 5 * y); // semicolon removed
F D I I I I // Float, Double or Int
All calculations in 1) are done in float
precision, in 2) in double
precision.
Suggestion: always prefer double
when using floating-point values.
CodePudding user response:
if you cast a floating point number less then 1 like 0.9f to INT, it will become zero.