输出错误.垃圾价值

Getting wrong output. Garbage value

本文关键字:错误 输出      更新时间:2023-10-16

问题是,在执行时,我得到的roundCost的值为大约1220673834。我发布整个程序是因为我不是确定我哪里错了。

注意:我被要求将所有变量都作为CCD_ 2类型,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中设置了主菜的餐费,但你从未将这个变量传递给类。我将其更改为使用构造函数来完成,该构造函数在创建时设置餐费。在您创建的每个类中,都应该始终添加一个构造函数。此外,您应该命名传递给函数的变量,然后在函数中使用相同的名称。例如,在税收百分比函数中,我传递双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语句并搜索您发现的错误,但这将为您提供一个有效的代码。