今天我试图编写一个程序来汇总用户输入的整数。例如,如果用户输入 683
它将返回 6 + 8 + 3 = 17。
但是我在代码中遇到了一些奇怪的问题
代码:
#includeusing namespace std;
int computeSum(int num);
int computeInteger(int num, int position);
int main()
{
int num;
int sum;
int total;
cin >> num;
total = computeSum(num);
cout << total;
return 0;
}
int computeSum(int num)
{
int position = 10;
int temp = num;
double total = 0;
bool finish = false;
while(!finish)
{
total = total + computeInteger(num, position);
if(num/ position == 0)
break;
position *= 10;
}
return total;
}
int computeInteger(int num, int position)
{
double subtract1 = (double) num / position; //if num = 683 and position = 10 , this will get 68.3
int subtract2 = num / position; //if num = 683 and position = 10 , this will get 68
double solution = subtract1 - subtract2; //take 68.3 - 68 = 0.3
return (int)(solution * 10); // return 0.3 * 10 = 3 , but instead of getting 3 this program return 0.3 * 10 = 2
}
问题
- 在上面的代码中,当我输入 683 时,对于函数
computeInteger
,而不是得到最后一个数字 3 我得到 2 作为返回值。这很奇怪,因为我认为截断只会删除 float 部分而不进行任何向上或向下舍入。当我测试代码时cout << (int)(0.3 * 10)
我确实得到了 3 ,但不是在上面的代码中。这让我很困惑。
最佳答案
double subtract1 = (double) num/position; //如果 num = 683 和 position = 10 ,这将得到 68.3
这不完全正确,0.3 不是以 2 为底数的有理数,它会非常接近 0.3 但会更小,因为数字总是向下舍入,为了缩小错误,您可以将其转换为 float 或long float 但事实并非如此,因为在你的例子中它总是 0.29,如果你想了解真正发生的事情你必须阅读计算机中的数字表示,这里有很好的描述:
http://en.wikipedia.org/wiki/Computer_number_format
您遇到的错误是众所周知的错误,在 wiki 页面中也有描述:
http://en.wikipedia.org/wiki/Round-off_error
和堆栈链接:
关于c++ - C++中的截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18653309/