我正在爲學校開展一個項目,無法將其整理出來。 這是我的代碼。首先,請原諒這個有趣的項目想法,並且隨我一起笑。這很有趣。它可能使編譯和運行它更容易看到我的問題。變量保留其值的問題
#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