簡體   English   中英

得到錯誤的輸出。 垃圾值

[英]Getting wrong output. Garbage value

問題是,在執行時,我得到的roundCost值類似於 -1220673834。 我發布了整個程序,因為我不確定我哪里出錯了。

注意:我被要求將所有變量都作為double類型,后來, roundCost應該是int類型。 所以我在那里使用了類型轉換。

#include<iostream>
using namespace std;

class Restaurant{ 

private:
double tip, tax,totalCost,mealCost, tipPercent, taxPercent;
int roundCost;
public:

int tipCalc(double)
    {
    tip=mealCost*(tipPercent/100);
    return tip;
    }

int taxCalc(double)
    {
    tax=mealCost*(taxPercent/100);
    return tax;
    }

int totalCost1()
    {
    totalCost=mealCost+tip+tax;
    return totalCost;
    }

int roundCost1(double)
    {
    roundCost=(int)totalCost;
    return roundCost;
    }   


}; // class ends
int main()
{
double mealCost, tipPercent, taxPercent, totalCost;
int roundCost;

Restaurant ob1;

cout<<"\n Enter mealCost \n";
cin>>mealCost;
cout<<"\n Enter mealtipPercent \n";
cin>>tipPercent;
cout<<"\n Enter mealtaxPercent \n";
cin>>taxPercent;
ob1.tipCalc(tipPercent);
ob1.taxCalc(taxPercent);
ob1.totalCost1();
ob1.roundCost1(totalCost);
cout<<"\n Round of cost is "<<roundCost<<endl;
return 0;
}

您似乎缺少的一件事是您的類中的變量與 main 中的變量具有不同的范圍。 您從 cin 在 main 中設置了膳食成本,但從未將此變量傳遞給類。 我將其更改為使用在創建時設置膳食成本的構造函數來完成。 在你創建的每個類中,你應該總是添加一個構造函數。 此外,您應該命名傳遞給函數的變量,然后在函數中使用相同的名稱。 例如,在稅收百分比函數中,我傳遞了 double t,t 是百分比,然后我們在計算中使用 t。 您的回合成本變量也是私有的,因此您需要通過函數輸出它。

此外 int 函數將返回一個值,如果您使用這種類型的函數,您應該將返回變量分配給某些東西,但由於您只是在類中設置內容,因此您可以對大多數情況使用 void 函數。 您在 main 中使用值的唯一時間是在 roundcost 中,因此最好讓它返回一個值。 因為它是 int (我假設你想要)它不會得到小數點,它會簡單地切斷總成本中的任何小數(即 75.75 將變成 75)。

#include<iostream>
using namespace std;

class Restaurant{ 

private:
double tip, tax,totalCost,mealCost;
int roundCost;
public:

Restaurant (double m)
{
    mealCost = m;
}

void tipCalc(double t)
{
    tip=mealCost*(t/100.0);
}

void taxCalc(double t)
{
    tax=mealCost*(t/100.0);
}

void totalCost1()
{
    totalCost=mealCost+tip+tax;
}

int roundCost1()
{
    roundCost=(int)totalCost;
    return roundCost;
} 

}; // class ends
int main()
{
    double mealCost, tipPercent, taxPercent, totalCost;
    int roundCost;


    cout<<"\n Enter mealCost \n";
    cin>>mealCost;
    Restaurant ob1(mealCost);
    cout<<"\n Enter mealtipPercent \n";
    cin>>tipPercent;
    cout<<"\n Enter mealtaxPercent \n";
    cin>>taxPercent;
    ob1.tipCalc(tipPercent);
    ob1.taxCalc(taxPercent);
    ob1.totalCost1();
    cout<<"\n Round of cost is "<<ob1.roundCost1()<<endl;
    return 0;
}

下次嘗試使用調試器進行更多研究,定期輸出 cout 語句並搜索您發現的錯誤,但這一次將為您提供工作代碼。

暫無
暫無

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

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