c - 返回一个 float 变量会失去其在 C 中的精度

标签 c function floating-point return

您好,是的,我在使用以下代码时遇到了一些问题。上面的函数执行并将 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

最佳答案

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

calcSigmaXY(max) 

你基本上是在说

int calcSigmaXY(max) 

因此精度损失 - 您返回的 float 被转换为 int。将您的函数声明为

float calcSigmaXY(max) {
      //...
}

关于c - 返回一个 float 变量会失去其在 C 中的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13575082/

相关文章:

c - C 代码的 Visual Studio 2010 Intellisense 曲线

c++ - 函数模板 : default type parameter

php function foo(array $arg = NULL) -- 为什么数组和 NULL?

.net - 程序集中的模板函数不可见

javascript - 修正JavaScript中浮点精度错误的算法

api - 使用 Lucene API 显示来自 Solr 索引的浮点字段

处理器的代码解释和十进制比较

c - C 语言中的 put() 指针

C:在文件中搜索内容

c - STM32将无符号短数组转换为 float 组