c++ - C++中的截断

标签 c++ floating-point truncation

今天我试图编写一个程序来汇总用户输入的整数。例如,如果用户输入 683它将返回 6 + 8 + 3 = 17。

但是我在代码中遇到了一些奇怪的问题

代码:

#include

using 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
 }

问题

  1. 在上面的代码中,当我输入 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

和堆栈链接:

What is a simple example of floating point/rounding error?

关于c++ - C++中的截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18653309/

相关文章:

c++ - 迭代对象 vector 并找到与从文本文件中提取的变量相匹配的变量

c - IEEE754中是否有关于加法的中性元素

ios - 跨 iOS 设备的 float 是否具有确定性?

Java:MySQL 数据截断:不正确的双值:列的 ''

python - 构建 RESTFul C++ api 以与 Python 交互

C++ 编译错误。 G++ 牛

c++ - 拆分 std::string 并插入 std::set

php - PHP中奇怪的数字转换错误

python 3.4 字符串操作 - 截断前导零

iphone - 带截断的多行 CATextLayer