4

嗨,是的,我在使用以下代码时遇到了一些问题。上面的函数执行并将 132.87 输出到 float 变量,但是当我将其返回到主程序时,输出会缩短为 132.00

这显然是我想念的简单的东西,有人可以帮我解决这个问题吗?非常感激。

calcSigmaXY(max) {
 int count= 0;
 float runTotal = 0, product[max];
 for (count = 1; count <= max; count++) {
     product[count] = pointData[count][1] * pointData[count][2];
     runTotal = runTotal + product[count];
 }
 printf("\nruntotal is %4.2f",runTotal); // outputs 132.87
 return(runTotal);
} 

int maxPoints = 6;
float sigmaXY = 0,
sigmaXY = calcSigmaXY(maxPoints);
printf("\nsigmaxy set to : %4.2f\n", sigmaXY); // outputs 132.00
4

2 回答 2

10

在某些 C 版本中,返回值和类型默认为int,因此通过声明您的函数

calcSigmaXY(max) 

你基本上是在说

int calcSigmaXY(max) 

ergo 精度损失 -float您返回的将转换为int. 将您的功能声明为

float calcSigmaXY(max) {
      //...
}
于 2012-11-26T23:43:06.053 回答
2

您必须声明 的返回值calcSigmaXY,否则返回值是int隐式的。

如果您声明您的函数float calcSigmaXY应该按预期工作。

还要考虑在您的编译器/IDE 中启用和读取警告。

于 2012-11-26T23:44:06.427 回答