【发布时间】:2021-03-18 05:17:22
【问题描述】:
底部的 C 代码通常按预期运行,在 Ubuntu 20.04 上使用 gcc,但大约 15% 的时间我得到 huge 最高温度的结果:
正常: 最高温度:15.30
15% 的时间: 最高温度:970363834813736688025683948382903403895871057............00
如果我将函数从 printf() 调用中提取出来,那么 100% 的情况都会按预期运行:
double max = maxTemp(temperatures,7);
printf("Highest temp: %.2lf\n", max);
我假设错误案例是一个巨大的数字,因为某处有一个带有垃圾数据的双精度数。
知道发生了什么吗?
感谢您的宝贵时间。
#include <stdio.h>
double maxTemp(double *temps, int numOfTemps);
int main(void) {
double temperatures[7] = {6.9, 12.3, 9.0, 15.3, 9.8, 1.8, 0.3};
printf("Highest temp: %.2lf\n", maxTemp(temperatures, maxTemp(temperatures,7)));
return 0;
}
double maxTemp(double *temps, int numOfTemps) {
double max = temps[0];
for (int i = 0; i < numOfTemps; i++) {
if (max < temps[i]) {
max = temps[i];
}
}
return max;
}
【问题讨论】:
-
我建议您添加更多
printf()语句来调试您的代码。 -
为什么要给
maxTemp()打两次电话? -
^ 那是你的错误。
-
一般来说,你的程序是完全确定的(当错误被修复时),没有任何竞争条件。
-
次要:
for (int i = 0; i < numOfTemps; i++)-->for (int i = 1; i < numOfTemps; i++)。无需测试temps[0]。