C++ 产量超过预期
我需要一个程序,其中用户订购物品,但输出错误。当我只需要2-3位数字时,它输出12位数字。为什么它输出的数字比预期的要大C++ 产量超过预期,c++,c++11,C++,C++11,我需要一个程序,其中用户订购物品,但输出错误。当我只需要2-3位数字时,它输出12位数字。为什么它输出的数字比预期的要大 #include <iostream> using namespace std; int main() { //Order int Pfries = 80, Pburgers = 150, Pdonuts = 30, Picecream = 25, Psoftdrinks = 20; int Nfries, Nburgers, N
#include <iostream>
using namespace std;
int main()
{
//Order
int Pfries = 80, Pburgers = 150, Pdonuts = 30, Picecream = 25, Psoftdrinks = 20;
int Nfries, Nburgers, Ndonuts, Nicecream, Nsoftdrinks;
int fries = Pfries * Nfries, burgers = Pburgers * Nburgers, donuts = Pdonuts * Ndonuts, icecream =
Picecream * Nicecream, softdrinks = Psoftdrinks * Nsoftdrinks;
string customer;
cout<<"Welcome to Murakani Cafe!"<<endl;
cout<< "Enter the name of the customer: ";
cin>>customer;
cout<< "Enter the number of fries ordered:";
cin>>Nfries;
cout<< "Enter the number of burger(s) ordered: ";
cin>>Nburgers;
cout<< "Enter the number of donut(s) ordered: ";
cin>>Ndonuts;
cout<< "Enter the number of ice cream ordered: ";
cin>>Nicecream;
cout<< "Enter the number of soft drink(s) ordered: ";
cin>>Nsoftdrinks;
//Output
cout<< "Hi "<< customer << "! Here is the summary of your order:"<<endl;
cout<<""<<endl;
cout<< Nfries << " fries "<< Pfries << fries <<endl;
cout<< Nburgers<< " burgers "<< Pburgers << burgers<<endl;
cout<< Ndonuts<< " donuts "<< Pdonuts << donuts<<endl;
cout<< Nicecream<< " ice cream "<< Picecream << icecream<<endl;
cout<< Nsoftdrinks<< " soft drinks "<< Psoftdrinks << softdrinks<<endl;
return 0;
}
#包括
使用名称空间std;
int main()
{
//命令
int Pfries=80,Pburgers=150,Pdonuts=30,Picecream=25,pSoftDivers=20;
国际食品、汉堡、坚果、奶油、饮料;
油炸薯条=Pfries*Nfries,汉堡=Pburgers*Nburgers,甜甜圈=pdoonuts*ndoonuts,冰淇淋=
Picecream*NiceScream,软饮料=PSOFTweedins*NSOFTweedins;
串客户;
甜甜圈;
奶油;
cout>nsoft饮料;
//输出
在C++中,你做事的顺序很重要。
int Pfries = 80;
cout<< "Enter the number of fries ordered:";
cin>>Nfries;
int fries = Pfries * Nfries;
在此计算中,在给定值之前使用Nfries
变量。这在技术上称为未定义行为,这是表示此代码的影响不可预测的另一种方式
你似乎在想,你写了一个公式:代码> FRES= pFRIES NFRIES < /Cord>,如果变量中的任何一个变量得到不同的值,C++将重新计算该公式,但这不是C++(或大多数编程语言)的方式。工作。相反,您的程序是一系列按给定顺序执行的语句,使用的值是执行给定语句时变量所具有的值。
int fries=Pfries*Nfries
但此时未初始化Nfries
。在用户在处输入之前不要使用它e> cin>>Nfries;
。请阅读,然后查看。
int Pfries = 80;
int fries = Pfries * Nfries;
cout<< "Enter the number of fries ordered:";
cin>>Nfries;