You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++找零计算器异常求助:小数末位为8/9时便士少1

问题原因

这是浮点数精度误差导致的问题。double 类型采用二进制浮点存储,无法精确表示部分十进制小数(比如0.39)。当你将这类小数乘以100时,实际得到的结果会略小于预期值(例如0.39*100实际存储为≈38.99999999999999),后续赋值给整数时会直接截断小数部分,导致便士数少1。

解决方案

在将美元小数部分转换为美分时,先对结果进行四舍五入,而非直接截断。可以使用C++标准库的round()函数(需要包含<cmath>头文件)来实现精确的四舍五入。

修正后的代码
#include <iostream>
#include <cmath> // 引入round函数所需头文件
using namespace std;

void ComputeChange(double totVal, int& numHundreds, int& numFifties, int& numTwenties, 
    int& numTens, int& numFives, int& numOnes, int& numQuarters, int& numDimes, int& 
    numNickels, int& numPennies) {
    double newVal;
    cout << "Your change:" << endl;
   
    numHundreds = totVal / 100;
    totVal -= (numHundreds * 100);
   
    numFifties = totVal / 50;
    totVal -= (numFifties * 50);
   
    numTwenties = totVal / 20;
    totVal -= (numTwenties * 20);
   
    numTens = totVal / 10;
    totVal -= (numTens * 10);
   
    numFives = totVal / 5;
    totVal -= (numFives * 5);
   
    numOnes = totVal / 1;
    totVal -= (numOnes * 1);
   
    // 关键修正:先四舍五入再计算美分
    newVal = round(totVal * 100);
    numQuarters = newVal / 25;
    newVal -= (numQuarters * 25);
   
    numDimes = newVal / 10;
    newVal -= (numDimes * 10);
   
    numNickels = newVal / 5;
    newVal -= (numNickels * 5);
   
    numPennies = newVal / 1;
}

int main() {
   
    double userVal;
    int numHundreds;
    int numFifties;
    int numTwenties;
    int numTens;
    int numFives;
    int numOnes;
    int numQuarters;
    int numDimes;
    int numNickels;
    int numPennies;

    cout << "Enter total amount: " << endl;
    cin >> userVal;

    cout << userVal << endl;

    ComputeChange(userVal, numHundreds, numFifties, numTwenties, numTens, numFives, numOnes, 
    numQuarters, numDimes, numNickels, numPennies);

    cout << "Hundreds: " << numHundreds << endl;
    cout << "Fifties: " << numFifties << endl;
    cout << "Twenties: " << numTwenties << endl;
    cout << "Tens: " << numTens << endl;
    cout << "Fives: " << numFives << endl;
    cout << "Ones: " << numOnes << endl;
    cout << "Quarters: " << numQuarters << endl;
    cout << "Dimes: " << numDimes << endl;
    cout << "Nickels: " << numNickels << endl;
    cout << "Pennies: " << numPennies << endl;

    return 0;
}
额外建议

从长远来看,使用double处理货币并非最佳实践,因为浮点数精度问题难以完全避免。更可靠的方式是用整数存储总美分数:

  • 输入时将金额转换为整数(例如153.39元=15339美分)
  • 全程使用整数运算,彻底消除浮点误差

内容的提问来源于stack exchange,提问作者oh juicez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 15:45:31