if
一. if语句
书P39例3-3:
#include <iostream>
using namespace std;
void main()
{
int a, b, max;
cout << "Please input two numbers: " << endl;
cin >> a >> b;
max = a;
if (max < b) max = b;
cout << "max=" << max << endl;
}
本project遇到的问题:
1.必须写成“if(<表达式>)语句”的形式吗?
if <表达式>
语句
的形式也可以,例:
#include <iostream>
using namespace std;
void main()
{
int a, b, max;
cout << "Please input two numbers: " << endl;
cin >> a >> b;
max = a;
if (max < b)
max = b;
cout << "max=" << max << endl;
}
2.cin输入时,保持输入>>,不要中途一般突然变成输入“,”
这样就会报错:变量未初始化。例:
#include <iostream>
using namespace std;
int main()
{
int a, b, max;
cout << "Please input two numbers: " << endl;
cin >> a , b;
max = a;
if (max < b) max = b;
cout << "max=" << max << endl;
}
3.cin输入时,输入多个变量,用“enter(换行键)”输入区分不同变量,而不是用“,”来区分,例:
此时无论变量b输入什么值,结果都只输出a
(因为使用“,”后默认忽略“,”后的b或默认“,”后为0)
4.VISUAL BASIC中的“if...then...”语句在C++中不成立
(if语句后面不能输入then),例:
#include <iostream>
using namespace std;
int main()
{
int a, b, max;
cout << "Please input two numbers: " << endl;
cin >> a >> b;
max = a;
if (max < b) then max = b;
cout << "max=" << max << endl;
}
二. if...else语句
书P39例3-4:
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "Please input two numbers:" << endl;
cin >> a >> b;
if (a > b)
cout << "max=" << a << endl;
else
cout << "max=" << b << endl;
}
三. if...else...if语句
书P40例3-5:
#include <iostream>
using namespace std;
int main()
{
char c;
cout << "input a character: " << endl;
cin >> c;
if (c < 32)
cout << "This is a control character." <<endl;
else if (c >= '0' && c <= '9')
cout << "This is a digit." <<endl;
else if (c >= 'A' && c <= 'Z')
cout << "This is an upper case letter." << endl;
else if (c >= 'a' && c <= 'z')
cout << "This is a lower case letter." << endl;
else
cout << "This is an other character." << endl;
}
注意:
输入字符串一样当作输出大写/小写字母来处理,例:
个人认为,这个 if...else...if语句,其实本质上来说并不是 if...else...if,而是 if...else if
因为 if...else...if 语句的效果(如下与书P40)所绘的流程图并不相同:
例:
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a ;
if (a==1)
cout << 1<< endl;
else
cout<< 2 << endl;
if (a == 2)
cout <<3 << endl;
}
结果:
为了验证第二个if语句是否在第一个if语句发生运行之后再运行,我们设计如下程序:
一.
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
if (a == 1)
{
cout << 1 << endl;
a++;//a=a++(先运算,后自增)
}
else
cout << 2 << endl;
if (a == 2)
cout << 3 << endl;
}
二.
#include <iostream>
using namespace std;
int main()
{
int a;
cin >> a;
if (a == 1)
{
cout << 1 << endl;
++a;
}
else
cout << 2 << endl;
if (a == 2)
cout << 3 << endl;
}
结果都是:
输入 | 输出 |
1 | 1 3 |
2 | 2 3 |
这两个程序同样的这样的结果,都说明了:
当输入a=1时,程序先运行第一个if语句,进行自增,然后再运行第二个if语句
也就是说:第二个if语句在第一个语句发生运行之后再运行。
证明了我们前面对于这个程序的流程图画。并没有画错。
所以,对于书上所想表达的意思,对应合理的语句应该是:
if...else if语句
这里我们讨论的都是C++中函数函数内还不含”{ }“的情况,
C语言中的一些规则以及内部使用”{ }“的情况,详情可参考:
C语言:if、if...else、if...else if ...else、if...if...if 语句的区别_斯文~的博客-CSDN博客_if if