这应该是一个简单的解决方法。因此,我试图将一段长度打印出来,以便将来用作变量。问题是变量不会正确初始化。 (忽略注释部分,因为我修复了这个问题)
问题出在这一行:double h = (1/m);
int main(void) {
int t = 1; //time
int m = 0; //number of segments of bar
int n = 0; //number of intervals related to time
printf("Enter number of segments: ");
scanf("%d", &m);
printf("Enter number of time intervals: ");
scanf("%d", &n);
printf("%d", m);
printf("\n");
double h = (1/m); //length of bar segments
double d = (1/n); //length of time interval
printf("%lf", h);
printf("\n");
printf("%d", m);
printf("\n");
}
我的输出:
Enter number of segments: 5
Enter number of time intervals: 10
5
0.000000
5
Program ended with exit code: 0
正确的输出不应该是0.00000,应该是0.20000。我意识到这可能是我想念的东西,但我似乎无法弄明白。
答案 0 :(得分:3)
double h = (1/m); //length of bar segments
double d = (1/n); //length of time interval
这些操作进行整数除法。尝试
double h = (1.0/m); //length of bar segments
double d = (1.0/n); //length of time interval
答案 1 :(得分:3)
整数计算被截断为整数值,即使您随后将它们分配给double
也是如此。想一想以下内容:
double h = 1 / m;
为:
1 / m
,截断,对绝大多数m
值都为零。double
(它仍为零)并将其分配给h
。这在ISO标准中指定,C11 6.5.5 Multiplicative operators /6
(我的斜体):
当整数被分割时,
/
运算符的结果是代数商与任何 分数部分丢弃。
您需要的是:
double h = 1.0 / m;
double d = 1.0 / n;
确保计算本身作为浮点数执行。