1.if语句
①注意的点:
1.单纯if语句,则满足条件执行,不满足条件跳过;
2.if-else语句,if满足条件,执行if,不满足条件,执行else,也就是说,语句必须执行一个。
3.if-else 语句要注意复合语句的用法,不能单独靠缩进。
②程序示例:
1.程序计算输入中的空格和字符总数
#include<iostream>
#include<string>
int main()
{
using namespace std;
cout << "Enter the sentence:(end with .)" << endl;
int num_all=0;
int num_spa=0;
char ch;
cin.get(ch);
while(ch !='.')
{
if (ch == ' ')
num_spa++;
num_all++;
cin.get(ch);
}
cout << num_spa << " spaces," << num_all << " characters total in sentence" << endl;
return 0;
}
2.字母加密,输出字符为输入字符加1
#include<iostream>
#include<string>
int main()
{
using namespace std;
cout << "Type,and I shall repeat." << endl;
char ch;
cin.get(ch);
while(ch !='.')
{
if (ch != '\n')
cout << ++ch; //cout << (char)(ch + 1);
else
cout << ch;
cin.get(ch);
}
return 0;
}
3.猜我最喜欢的数字
#include<iostream>
#include<string>
int main()
{
const int my_number = 27;
using namespace std;
cout << "Enter a number in the range 1-100 to find my favorite number:";
int guess = 0;
cin >> guess;
while (guess != my_number)
{
if (guess > my_number)
cout << "Too high -- guess gagin:";
else
cout << "Too low -- guess gagin:";
cin >> guess;
}
cout <<my_number<< " is right" << endl;
return 0;
}
2.逻辑表达式
①介绍:
|| ——只需满足一个条件即可,只要一个成立,后边不会再计算
示例——字母大小写的问题
#include<iostream>
#include<string>
int main()
{
using namespace std;
cout << "This program may reformat your hard disk\n"
<< "and destroy all your data."
<< "Do you wish to continue?<y/n>";
char ch;
cin.get(ch);
if (ch == 'y' || ch == 'Y')
cout << "you were warned!\a\a\n";
else if (ch == 'n' || ch == 'N')
cout << "A wise choice .. bye" << endl;
else
cout << "That wasn't a y or n!";
return 0;
}
&&——两个条件同时满足,用于两种不同原因结束循环,可用&&;设置取值范围也可以与
示例: 满足输入大于6个或输入负值结束。
#include<iostream>
int main()
{
const int Size = 6;
using namespace std;
cout << "Enter the NAAQs(New Age Awareness Quotients) of\n"
<< "your neighbors. Program terminates when you make\n"
<< "6 entries or enter a negative value.\n"
<< "Frist value:";
int temp[Size];
int i = 0;
cin >> temp[0];
while (i < Size-1 && temp[i] >= 0)
{
i++;
cout << "Next value:";
c