输出错误.垃圾价值
Getting wrong output. Garbage value
问题是,在执行时,我得到的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语句并搜索您发现的错误,但这将为您提供一个有效的代码。
相关文章:
- 显示错误输出的简单数组排序程序
- Dijkstra 中的错误输出
- 自定义runtime_error,如果我在 #what 中使用#c_str(),则错误输出始终为空
- 流字符串错误输出
- C++ 异常处理错误输出
- C ++中的错误输出,i = 65530,当我们打印i的值时,它给出-6状态65530
- SSE和iostream:浮点类型的错误输出
- C++将 popen 错误输出读取为字符串
- 部分透视/高斯消除 - 交换列而不是产生错误输出的行
- C++,向量:获得包含 0 的错误输出
- 数组函数错误输出
- CC1plus 错误:输出文件名指定两次
- 字符串错误输出
- 子斯特的错误输出
- 对大量c++错误输出完全一无所知.我认为这与预定义的函数和迭代器有关
- 简单程序的错误输出
- XCode调试器lldb中断,没有错误输出,但程序运行良好
- std::string::append(std::string)错误输出
- 查看大错误输出的顶行
- 使用结构的错误输出