【发布时间】:2014-03-07 06:45:12
【问题描述】:
为什么我会在 c++ 中将 int 转换为错误的浮点数?在程序中的某个时刻,我将一个值为 10 或 14 的整数显式转换为浮点数,我得到 0。为什么会这样?我尝试了 static_cast,给了我同样的结果。由于 int 和 float 都是 4 个字节,我认为 int 到 float 的转换不是按大小降级或提升吗?它与舍入误差等有关吗?谁能解释一下。
这里是代码(这里有一个改动很好,但我还是不知道为什么)---
#include <iostream>
using namespace std;
int main()
{
int n;
int sum;
cout << "Please enter the number:";
cin >> n;
int *elements = new int[n];
cout << "Please enter the elements:";
for(int i=0; i<n; i++)
{
cin >> elements[i];
}
cout << endl;
///// this approach, gives the sum right, but float(sum) fails and always gives zero.
for(int i=0, sum=0; i < n; i++)
{
sum = sum + elements[i];
}
////// This works, when sum is initialised outside of for loop. float(sum) does the right conversion as well.
//sum = 0;
//for(int i=0; i < n; i++)
//{
// sum = sum + elements[i];
//}
cout << " float n is " << float(n) << " float sum is "<< float(sum) << endl;
// float(sum) is zero, when sum is initialised from within for loop.
delete[] elements;
return 0;
}
编译命令 -> g++ 3.2.cpp -o 3.2
输入:n = 4;元素 = 1 2 3 4
感觉像是我忽略了一些小事。
感谢您的帮助。
【问题讨论】:
-
除非您实际向我们展示您所描述的内容,否则我们无法解释。
-
不看代码谁也说不准。
-
在重复问题中,整数不会转换为浮点数进行操作。在这种情况下,转换后我得到了错误的答案。
-
Seems to work fine for me(注意底部的标准输出是
float n is 2 float sum is 24)。
标签: c++ scope explicit-conversion