C语言 C - 如何划分浮点数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5183141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C - how to divide floats?
提问by Waypoint
I get input from command line as a int d. Now I am facing this problem:
我从命令行输入 int d。现在我面临这个问题:
float a,b;
int d;
float piece;
printf("Please enter the parts to divide the interval: ");
scanf("%d", &d);
a=0;
b=1;
piece=b-a/(float)d;
printf("%f\n",piece);
All I want is to printf some float number dependent on &d. e.g. when I write here 5, I would get 0.20000, for 6 - 0,166666 but I am still getting 1.000000 for all numbers, does anyone knows solution?
我想要的只是打印一些依赖于 &d 的浮点数。例如,当我在这里写 5 时,对于 6 - 0,166666,我会得到 0.20000,但对于所有数字,我仍然得到 1.000000,有人知道解决方案吗?
回答by Vamana
Division has precedence over subtraction, so you need to put the subtraction inside parentheses. You don't have to explicitly cast d to float; dividing a float by it will promote it to float.
除法优先于减法,因此您需要将减法放在括号内。您不必显式地将 d 强制转换为浮动;除以浮点数将促进它浮动。
piece = (b - a) / d;
回答by Sjoerd
Use parenthesis:
使用括号:
piece=(b-a)/(float)d;
回答by Stephen Canon
I believe you want:
我相信你想要:
piece = (b - a)/d;
I.e., the problem isn't division, but order of operations.
即,问题不是除法,而是运算顺序。
回答by Brian Driscoll
I think this line:
piece=b-a/(float)d;
我认为这一行:
piece=b-a/(float)d;
should be:
piece=(float)(b-a)/(float)d;
应该:
piece=(float)(b-a)/(float)d;
Just my 2 cents.
只有我的 2 美分。
EDIT
编辑
Since dis an int, perhaps try this instead:
由于d是一个整数,也许可以试试这个:
piece=(float)((b-a)/d);
piece=(float)((b-a)/d);

