Why I am getting zero in float expressions like 1/2?
4597 просмотра
2 ответа
Can please someone explain this behavier :
#include <stdio.h>
int main(int argc, char **argv){
printf("%f", ( 1 / 2 ) );
return 0;
}
/* output : 0.00000 */
Автор: Tiger
Источник
Размещён: 12.11.2019 09:52
Ответы (2)
2 плюса
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 +
, -
, *
, and /
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 1
and 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 int
value 0
.
So the above is equivalent to:
printf("%f", 0);
The "%f"
format requires an argument of type double
; 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 "%d"
:
printf("%d", 1 / 2);
But you probably want 0.5
. You can get that by using operands of type double
:
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:
printf("%f\n", 1.0 / 2.0);
Автор: Keith Thompson
Размещён: 27.06.2015 05:27
1 плюс
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:
printf("%f", ( 1 / 2.0 ) ); ,
Вопросы из категории :
- c Как вы форматируете unsigned long long int, используя printf?
- c What are the barriers to understanding pointers and what can be done to overcome them?
- c Как реализовать продолжения?
- c Как вы передаете функцию в качестве параметра в C?
- c Как получить список каталогов в C?
- c В чем разница между #include <filename> и #include "filename"?
- c Всегда ли выгодно использовать «goto» в языке, который поддерживает циклы и функции? Если так, то почему?
- c В чем разница между ++ i и i ++?
- c Есть ли разница в производительности между i ++ и ++ i в C?
- c Какой самый лучший бесплатный детектор утечки памяти для программы на C / C ++ и ее подключаемых библиотек DLL?
- floating-point Преобразовать десятичную в двойную?
- floating-point Как вручную проанализировать число с плавающей запятой из строки
- floating-point Плавающая / двойная точность в режимах отладки / выпуска
- floating-point Сохраняйте точность с двойным в Java
- floating-point Насколько детерминистична погрешность с плавающей запятой?
- floating-point Как проверить, является ли строка числом (с плавающей запятой)?
- floating-point Как мне разобрать строку с плавающей точкой или int в Python?
- floating-point Как лучше суммировать много чисел с плавающей точкой?
- floating-point «Приближенный» наибольший общий делитель
- floating-point Ограничение числа с плавающей точкой до двух десятичных знаков