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

C++中如何用初始声明的int值输出double类型除法结果?

解决int成员变量的除法返回double结果问题

问题核心在于:你的divide()函数中,a / b执行的是整数除法。因为a和b都是int类型,C++会优先进行整数运算(直接截断小数部分),再将结果转换为double返回,所以最终输出的还是整数除法的结果。

解决方法

只需要在除法运算前,将其中一个操作数强制转换为double类型,让编译器触发浮点除法即可:

double divide() const{
    // 将a强制转为double,此时b会自动提升为double参与运算
    return static_cast<double>(a) / b;
}

额外优化:处理除零错误

如果输入的b为0,会触发运行时错误,建议在divide函数中增加判断:

double divide() const{
    if (b == 0) {
        cerr << "错误:除数不能为0!" << endl;
        return NAN; // 返回非数值标记,需要包含<cmath>头文件
    }
    return static_cast<double>(a) / b;
}

修改后的完整代码

#include <iomanip>
#include <iostream>
#include <cmath>

using namespace std;

class Calculator{
    private:
        int a = 0;
        int b = 0;

    public:
        Calculator(int n1, int n2) : a(n1), b(n2) {}

        Calculator() = default;

        int getN1() const{
            return a;
        }

        int getN2() const{
            return b;
        }
        
        int add() const{
            return a + b;
        }
    
        int subtract() const{
            return a - b;
        }
    
        int multiply() const{
            return a * b;
        }
        
        double divide() const{
            if (b == 0) {
                cerr << "错误:除数不能为0!" << endl;
                return NAN;
            }
            return static_cast<double>(a) / b;
        }
  
    void showDetails() const{
        cout << "\nComputed:" << endl;
        cout << "Sum = " << add() << endl;
        cout << "Difference = " << subtract() << endl;
        cout << "Product = " << multiply() << endl;
        cout << "Quotient = " << setprecision(2) << fixed << divide() << endl;
    }
};

int main() {
    int n1;
    int n2;

    cout << "Enter Num1: ";
    cin >> n1;
    cout << "Enter Num2: ";
    cin >> n2;

    Calculator x(n1, n2);
    x.showDetails();

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:40:26