c ++错误:否则没有先前的if

时间:2012-07-03 05:47:26

标签: c++ if-statement syntax-error

只是制作一个小程序来开始c ++,并且编译器说有一个没有if引用于while中的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;
}

3 个答案:

答案 0 :(得分: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语句中有多个操作,则应始终使用括号。如果你只有一个,你也可以省略它们(如在“其他”声明中)。

答案 1 :(得分:2)

{之前需要if (newnum != 0)}之前需要else

答案 2 :(得分: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
}