C - 如何划分浮点数?

发布于 2024-10-20 07:04:12 字数 339 浏览 9 评论 0原文

我从命令行获取 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);

我想要的只是打印一些依赖于 &deg 的浮点数,当我在这里写 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

浅笑轻吟梦一曲 2024-10-27 07:04:12

除法优先于减法,因此需要将减法放在括号内。您不必显式地将 d 转换为 float;将一个浮点数除以它会促使它浮动。

piece = (b - a) / d;

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.

piece = (b - a) / d;
滥情稳全场 2024-10-27 07:04:12

使用括号:

piece=(b-a)/(float)d;

Use parenthesis:

piece=(b-a)/(float)d;
红尘作伴 2024-10-27 07:04:12

我相信你想要:

piece = (b - a)/d;

即,问题不是除法,而是运算顺序。

I believe you want:

piece = (b - a)/d;

I.e., the problem isn't division, but order of operations.

堇色安年 2024-10-27 07:04:12

我认为这一行:
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);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文