今天我正在尝试编写一个程序来总结用户输入的整数。例如,如果用户输入683它将返回 6 + 8 + 3 = 17。
但是我在代码中遇到了一些奇怪的问题
编码 :
#包括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
 }
问题
- 在上面的代码中,当我为函数输入 683 时,我
computeInteger没有得到最后一个数字 3,而是得到 2 作为返回值。这很奇怪,因为我认为截断只会删除浮动部分而不会向上或向下进行任何舍入。当我测试代码cout << (int)(0.3 * 10)时,我确实得到了 3 ,但在上面的代码中没有。这让我很困惑。