-5

只是制作一个小程序来启动 c++,编译器说有一个没有 if 的 else 来引用 main 中的 while 循环,但显然不是这样,我不明白为什么。如果我删除 while 循环,它工作正常。

#include <iostream>
using namespace std;

int number;

int arithmetic(int num)
{
 if(num > 20)
  num = num * 5;
 else 
  num = 0;
 return (num);
}

int main()
{ 
 int wait;
 cout <<  "I will take any number providing it is higher than twenty" << endl;
 cout <<  "and I will multiply it by 5. I shall then print every number" << endl;
 cout <<  "from that number backwards and say goodbye." << endl; 
 cout <<  "Now please give me your number: " << endl;
 cin >> number;
 int newnum = arithmetic(number);
 if (newnum != 0)
  cout << "Thank you for the number, your new number is" << newnum << endl;
  while(newnum > 0){
   cout << newnum;
   --newnum;
  }
  cout << "bye";
 else
  cout << "The number you entered is not greater than twenty";
 cin >> wait;
 return 0;
}
4

3 回答 3

3

你缺少括号。你有

if (newnum != 0)
cout << "Thank you for the number, your new number is" << newnum << endl;
while(newnum > 0){
cout << newnum;
--newnum;
 }
cout << "bye";
else
cout << "The number you entered is not greater than twenty";

而你应该有:

if (newnum != 0)
{
   cout << "Thank you for the number, your new number is" << newnum << endl;
   while(newnum > 0){
   cout << newnum;
   --newnum;
   cout << "bye";
}
else
    cout << "The number you entered is not greater than twenty";

如果 if 语句中有多个操作,则应始终使用括号。如果你只有一个,你也可以省略它们(就像在这个“else”语句中一样)。

于 2012-07-03T05:50:46.290 回答
2

你需要一个{afterif (newnum != 0)和一个}before else

于 2012-07-03T05:48:52.593 回答
2

这种结构是错误的:

if(something)
  line1;
  line2; // this ; disconnects the if from the else
 else 
  // code

你需要类似的东西

if ( something ) {
  // more than one line of code 
} else  {
  // more than one line of code
}
于 2012-07-03T05:50:05.530 回答