簡體   English   中英

如果我的代碼出錯了,有人可以看看嗎?

[英]Could someone look over were I went wrong in my code?

我正在做另一個編碼練習,我的代碼沒有給我正確的答案。

例如:

早上總產奶量是多少:3590.56

  • 紙箱數量 = 949 應該是 950
  • 生產成本 = 1364.41 正確
  • 生產利潤 = 256.47 應該是 256.5

下面是我的代碼

#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>

using namespace std;

const double CARTON = 3.78;
const double PRODUCECOST = 0.38;
const double PROFIT = 0.27;

int main() {
    double milkProduced, numCartons;
    double costOfProducing, profitOfProducing;

    cout << fixed << showpoint << setprecision(2);

    cout << "What was the total amount of milk produced in the morning: " << endl;
    cin >> milkProduced;

    numCartons = milkProduced / CARTON;
    costOfProducing = milkProduced * PRODUCECOST;
    profitOfProducing = numCartons * PROFIT;

    cout << static_cast<int>(numCartons) << endl;
    cout << costOfProducing << endl;
    cout << profitOfProducing << endl;

    return 0;
}

這非常接近,但是您的num_cartons值實際上是949.883...並且,當您將其轉換為int時,它會截斷小數部分而不是舍入它。

此外,您只對output執行此操作,並且不要將該更改反饋回變量以進行后續計算(特別是利潤)。

我建議,而不是這樣做,你嘗試:

numCartons = round(milkProduced / CARTON); // needs <cmath>

設置值。

這將使紙箱的數量成為一個整數值,或者足夠接近課堂作業。 換句話說:

#include<iostream>
#include<string>
#include<iomanip>
#include<fstream>
#include<cmath>

using namespace std;

const double CARTON = 3.78;
const double PRODUCECOST = 0.38;
const double PROFIT = 0.27;

int main() {
    double milkProduced, numCartons;
    double costOfProducing, profitOfProducing;

    cout << fixed << showpoint << setprecision(2);

    cout << "What was the total amount of milk produced in the morning: " << endl;
    cin >> milkProduced;

    numCartons = round(milkProduced / CARTON);
    costOfProducing = milkProduced * PRODUCECOST;
    profitOfProducing = numCartons * PROFIT;

    cout << numCartons << endl;
    cout << costOfProducing << endl;
    cout << profitOfProducing << endl;

    return 0;
}

其中的 output 更符合您的期望:

> ./testProg
What was the total amount of milk produced in the morning: 3590.56
950.00
1364.41
256.50

正如評論中指出的那樣,您可能應該截斷而不是四舍五入,因為您很可能不會出售部分裝滿的容器(或者如果您在道德上模棱兩可的話,可以加水)。

但是,即使是這種情況,您也應該修改變量,使其影響利潤數字,而不是僅僅輸出四舍五入的值並使用原始值。

自從你說950是正確的紙箱數后,我才四舍五入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM