我是初学者学习代码,我正在复制用于编程教学的YouTube视频。但是当我编写代码时,它会导致一些错误。
以下是代码:
#include <iostream>
using namespace std;
int main()
{
int num1 , num2;
cout<< " Enter number 1 and number 2 \n";
cin>> num1 >> num2;
if (num1 == num2);
cout<< "The both numbers are equal \n";
else if (num1> num2)
cout<< "Number 1 is greater than number 2 \n";
else (num1< num2)
cout<< "Number 2 is greater than number 1 \n";
return 0;
}
答案 0 :(得分:8)
请注意,;
表示表达式结束,因此您应该更改
if (num1 == num2);
到
if (num1 == num2)
且else
不需要条件,因此请更改
else (num1< num2)
到
else
答案 1 :(得分:1)
;
条件检查后您不需要if
如果您想进行条件检查,则应使用else if
,在这种情况下else
是不够的:
#include <iostream>
using namespace std;
int main()
{
int num1 , num2;
cout<< " Enter number 1 and number 2 \n";
cin>> num1 >> num2;
if (num1 == num2)
cout<< "The both numbers are equal \n";
else if (num1> num2)
cout<< "Number 1 is greater than number 2 \n";
else if (num1< num2)
cout<< "Number 2 is greater than number 1 \n";
return 0;
}
答案 2 :(得分:1)
; is not placed after `if` condition
此外,否则没有得到条件......它总是检查对应的if的否定。
实际上,如果if
的条件不能保存else
块中的代码,则执行....通过更改
else (num1< num2)
cout<< "Number 2 is greater than number 1 \n";
到
else
cout<< "Number 2 is greater than number 1 \n";
你的问题将得到解决。