C - 如何划分浮点数?
我从命令行获取 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);
我想要的只是打印一些依赖于 ° 的浮点数,当我在这里写 5 时,我会得到 0.20000,对于 6 - 0,166666 但我仍然得到所有数字的 1.000000,有人吗知道解决办法吗?
I get input from command line as a int d. Now I am facing this problem:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除法优先于减法,因此需要将减法放在括号内。您不必显式地将 d 转换为 float;将一个浮点数除以它会促使它浮动。
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.
使用括号:
Use parenthesis:
我相信你想要:
即,问题不是除法,而是运算顺序。
I believe you want:
I.e., the problem isn't division, but order of operations.
我认为这一行:
piece=ba/(float)d;
应该是:
piece=(float)(ba)/(float)d;
只是我的 2 美分。
编辑
由于
d
是一个int,也许可以试试这个:piece=(float)((ba)/d);
I think this line:
piece=b-a/(float)d;
should be:
piece=(float)(b-a)/(float)d;
Just my 2 cents.
EDIT
Since
d
is an int, perhaps try this instead:piece=(float)((b-a)/d);