Why I am getting zero in float expressions like 1/2?
283 Репутация автора
176 Репутация автора
Exactly what quantdev said. The people who wrote the C language thought something along the lines of "hey let's just make the dividend of any two integers an integer, because integers are super useful and maybe getting a float would mess with your style when you're trying to index an array". So the C Compiler proceeds to toss the remainder into the garbage and you're left with 0.
1 / 2
To declare that you want your darn double, ( or float ) you better make one of the two numbers in the division a float! Thus,
1 / 2.0
and, in context...
not what you want:
printf("%f", ( 1 / 2 ) ); ,
what you want:
Размещён: 27.06.2015 03:50
printf("%f", ( 1 / 2.0 ) ); ,
204783 Репутация автора
1 / 2 is not a floating-point expression.
printf("%f", ( 1 / 2 ) );
The inner parentheses are unnecessary; this is a bit easier to read as:
printf("%f", 1 / 2);
In most cases, the type of an expression in C is determined by the expression itself, not by the context in which it appears. This applies even to subexpressions of larger expressions.
The arithmetic operators
/ always take two operands of the same numeric type, and yield a result of that type. There are rules to convert the operands to a common type, but
2 are both of type
int, so we needn't worry about that. All these operators, if invoked with
int operands, yield an
int result. Integer division truncates, discarding any remainder, so
1 / 2 yields the
So the above is equivalent to:
"%f" format requires an argument of type
0 is of type
int. For most functions, there would be an implicit conversion, but the types of the parameters are determined by the format string, not by the function declaration, so the compiler doesn't know what type to convert to. (Consider that the format string doesn't have to be a string literal.) Passing an
int argument with a
"%f" format has undefined behavior. In your case, it just happened to print
0. We could speculate about how that happened, but it doesn't matter; you need to fix the code.
If you wanted to print that
int value, you could use
printf("%d", 1 / 2);
But you probably want
0.5. You can get that by using operands of type
printf("%f", 1.0 / 2.0);
(You could change just one of the two operands to a floating-point constant, but it's clearer to change both.)
Finally, you should print a newline at the end of your output:
Автор: Keith Thompson Размещён: 27.06.2015 05:27
printf("%f\n", 1.0 / 2.0);