我正在为学校开展一个项目,无法将其整理出来。 这是我的代码。首先,请原谅这个有趣的项目想法,并且随我一起笑。这很有趣。它可能使编译和运行它更容易看到我的问题。变量保留其值的问题
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
const int z=6;
const int m=rand()%z;
const int c=rand()%z;
const int p=rand()%z;
const int l=rand()%z;
int inventory(){
//This reports the current status of the machine
int money;
setprecision(3);
cout<<"after calling inventory function but before cout portion "<<money<<endl;
cout<<"\nThere are "<<m<<" Marlboro packs\n";
cout<<"There are "<<c<<" Camel packs\n";
cout<<"There are "<<p<<" Pall Mall packs\n";
cout<<"There are "<<l<<" Lucky Strikes packs\n";
cout<<"You have inserted $";
cout<<money;
cout<<". You need $1 to purchase one pack\n\n";
}
char GetAction(){
char action='a';
cout<<"What would you like to do?\n";
cout<<"d = drop in a quarter\n";
cout<<"1 = pull the first knob\n";
cout<<"2 = pull the second knob\n";
cout<<"3 = pull the third knob\n";
cout<<"4 = pull the 4th knob\n";
cout<<"r = restock the machine\n";
cout<<"s = read status of machine\n";
cout<<"q = surrender your money\n\n";
while (true){
cout<<"-";
cin>>action;
if(action=='d')return action;
if(action=='1')return action;
if(action=='2')return action;
if(action=='3')return action;
if(action=='4')return action;
if(action=='r')return action;
if(action=='s')return action;
if(action=='q')return action;
cout<<"Please try again\n";
}
}
int main(){
char action='a';
setprecision(3);
int money=0;
cout<<"Welcome to the Art-o-Mat Cigarette Dispenser.\n";
cout<<"current money value before loop "<<money<<endl;
while(action!='q'){
action=GetAction();
switch(action){
case 'd':
if(money<1){
cout<<"- - - - - -\n- - - - - - \n- kaching! -\n- - - - - -\n- - - - - -\n\n";
setprecision(3);
money=(money+0.25);
cout<<"current money value after increase drop quarter "<<money<<endl;
}
else{
cout<<"Don't you begin to think you can take advantage of a machine like me\n- - - (your quarter is vigorously tossed out the coin reject) - -\n\n";
return GetAction();
}
break;
case 's':
cout<<"current money value before calling inventory function "<<money<<endl;
inventory();
break;
default:
break;
}
}
return 0;
}
如果很明显,代码的意图是用变量发挥和保留信息,从自动售货机购买香烟。我知道它的老派和一些跛脚。我的教授写了作业和细节,而不是我。
无论如何,我的“钱”变量的价值不被保留。我在cout语句中加入了整个代码中的进度,如果你自己没有运行它,它会在开关函数中运行's'的情况和在库存函数中被调用之间改变。它从0变化到某些未知的2147348480.另外,当下面的情况'd'时,该值不会像应该那样增加。
我对C++很陌生,但对jargan或C++的谈话非常熟悉。除非我已经搞砸了..任何意见表示赞赏!谢谢! -Taylor
打开警告。始终打开警告。谈论一个编写警告的程序是毫无意义的浪费时间(除非你想谈论当然的警告)。投票结束。 – 2014-09-20 08:04:05
这个问题似乎无关紧要,因为它关注的不是编译器警告。 – 2014-09-20 08:04:47
你的代码中有两个完全不相关的'money'变量。一个在'main'里面,一个在'inventory'里面。你在说哪一个? “库存”内的一个甚至没有初始化,这意味着它包含垃圾值。 – AnT 2014-09-20 08:07:32