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

C++中pair<double, double>类型函数调用无响应问题求助

问题修复与代码优化

修复后的完整代码

#include <iostream>
#include <vector>
#include <utility>

using namespace std;

pair<double, double> total(const vector<double>& itemPrices, double taxRate)
{
    double sum = 0.0;
    for (double price : itemPrices)
    {
        sum += price;
    }
  
    double totalWithTax = sum * (1 + taxRate);
    return {sum, totalWithTax};
}

int main()
{
    int itemCount = 0;
    cout << "Enter the number of items: ";
    cin >> itemCount;
    vector<double> itemPrices(itemCount);
    cout << "Enter item prices: " << endl;
  
    for(int i = 0; i < itemCount; ++i)
    {
        cin >> itemPrices[i];
    }

    double taxRate = 0.0;
    cout << "Enter tax rate (e.g., 0.0825 for 8.25%): ";
    cin >> taxRate;
  
    pair<double, double> val = total(itemPrices, taxRate);
    double totalWithoutTax = val.first;
    double totalWithTax = val.second;

    // 输出计算结果
    cout << "Total without tax: " << totalWithoutTax << endl;
    cout << "Total with tax: " << totalWithTax << endl;

    return 0;
}

原代码的问题与修复说明

  • 无结果输出:原main函数仅计算了结果但未通过cout打印,程序执行后直接退出。修复后添加了结果输出语句,让你能看到计算后的不含税总价和含税总价。
  • 总价计算逻辑错误:原total函数循环内sum += i是累加循环索引,而非商品价格。修复后改为累加itemPrices中的实际价格,用范围for循环更简洁直观。
  • 未支持自定义税率:原函数硬编码了税率0.0825,不符合“接收任意税率”的需求。修复后将税率作为参数传入函数,并在main中添加了税率输入步骤。
  • 参数传递效率低:原函数中vector<double> itemPrices采用传值方式,会触发不必要的容器拷贝。改为const vector<double>& itemPrices传const引用,避免拷贝开销。
  • 头文件冗余:去掉了过于庞大的<bits/stdc++.h>,显式包含所需的<iostream>、<vector>、<utility>头文件,代码更清晰且编译速度更快。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:40:22