就是一個簡單地計算器,能處理一串輸入程序是沒有什么問題的,但是我看不懂為什么expr()函數里的value會顯示出來??expr()里面不是沒有return value這句嗎疑惑啊 哪位指點一下#include <iostream>#include<cstdlib>#include<cctype>using namespace std;void eatspaces(char* str);double expr(char* str);double term(char* str,int& index);double number(char* str,int& index);const int MAX =80;int main(){char buffer[MAX]={0};cout<<endl<<"Welcome!"<<endl<<"Enter an expression,or an empty line to quit."<<endl;for(;;){cin.getline(buffer,sizeof buffer);eatspaces(buffer);if(!buffer[0])return 0;cout<<"="<<expr(buffer)<<endl;}}void eatspaces(char* str){int i=0;int j=0;while((*(str+i)=*(str+j++))!='\0')if(*(str+i)!=' ')i++;return;}//Function to evaluate an arithmetic expressiondouble expr(char* str){double value=0.0;int index=0;value=term(str,index);for(;;)switch(*(str+index++)){case '\0':return value;case '+':value+=term(str,index);break;case '-':value-=term(str,index);break;default:cout<<endl<<"Arrrgh!*#!! There's an error"<<endl;exit(1);}}//Function to get the value of a termdouble term(char* str,int& index){double value=0.0;value=number(str,index);while((*(str+index)=='*')||(*(str+index)=='/')){if(*(str+index)=='*')value *=number(str,++index);if(*(str+index)=='/')value /=number(str,++index);}return value;}//Function to recognize anumber in a stringdouble number(char* str,int& index){double value =0.0;while(isdigit(*(str+index)))value=10*value+(*(str+index++)-'0');if(*(str+index)!='.')return value;double factor=1.0;while(isdigit(*(str+(++index)))){factor *=0.1;value=value+(*(str+index)-'0')*factor;}return value;}程序是沒有什么問題的,當時我看不懂為什么expr()函數里的value會顯示出來??expr()里面不是沒有return value這句嗎疑惑啊 哪位指點一下
2 回答

MYYA
TA貢獻1868條經驗 獲得超4個贊
有 return 啊,
for(;;)
switch(*(str+index++))
{
case '\0':
return value; //這句就是返回值啊,for循環無限switch 直到case‘\0’就return value;
case '+':
value+=term(str,index);
break;
case '-':
value-=term(str,index);
break;
default:
cout<<endl
<<"Arrrgh!*#!! There's an error"
<<endl;

MM們
TA貢獻1886條經驗 獲得超2個贊
怎么沒有return value啊。
double expr(char* str)
{
double value=0.0;
int index=0;
value=term(str,index);
for(;;)
switch(*(str+index++))
{
case '\0':
return value;//這里不是嗎。
case '+':
value+=term(str,index);
break;
case '-':
value-=term(str,index);
break;
default:
cout<<endl
<<"Arrrgh!*#!! There's an error"
<<endl;
exit(1);
}
}
- 2 回答
- 0 關注
- 244 瀏覽
添加回答
舉報
0/150
提交
取消