Eli*_*ims 2 c scanf integer-division
我正在尝试编写一个公式来计算球体的体积,用户输入半径.公式是V = (4/3)PI r*r*r.我无法弄清楚为什么我的代码只是说无论输入是什么,音量都是1.这是我正在使用的:
#include <stdio.h>
int main(void) {
float pi, r, v;
pi = 3.1416;
printf("What is the radius?\n");
scanf("%d", &r);
v = ((4/3) * pi) * r * r * r;
printf("Volume of the sphere is: %d\n", v);
if (v>10)
printf("Volume is greater than 10");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我认为有很多问题.
首先,
scanf("%d", &r);
Run Code Online (Sandbox Code Playgroud)
应该
scanf("%f", &r);
Run Code Online (Sandbox Code Playgroud)
就像r一个float.将不兼容的类型作为参数传递会导致未定义的行为.请仔细检查格式说明符和提供的参数类型.
同样适用于
printf("Volume of the sphere is: %d\n", v);
Run Code Online (Sandbox Code Playgroud)
另外,正如%f 预期的那样float(或者double,确切地说,a float,在默认参数促销之后被提升为a double),而不是 %d.
启用其他选项后,编译器可能会警告您不匹配(至少gcc可以这样做).启用所有警告,它应该为您指出问题.
然后,以后
v = ((4/3) * pi) * r * r * r;
Run Code Online (Sandbox Code Playgroud)
该4/3收益率的整数除法(给1),所以它不会做什么,你认为它.如果需要,您需要强制执行浮点除法,例如:
v = (pi * 4 / 3) * r * r * r;
Run Code Online (Sandbox Code Playgroud)
(其中,float pi乘以4给出了一个浮子,其保持一个float分割时3).
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |