C++入门——Day5_分支语句和逻辑运算符
一、if语句
if语句的语法和while类似
if(test-condition)
statement
比如:假设读者希望程序计算输入的空格数和字符总数,则可以在while循环使用cing.get(char)读取字符,使用if预计识别空格字符并计算,使用.确定句尾
#include <iostream>int main(void)
{using namespace std;int spaces = 0;int total = 0;char ch;cin.get(ch);while (ch != '.') {if(ch == ' '){++spaces;}++total; cin.get(ch);}cout << "spaces = " << spaces << endl;cout << "total = " << total << endl;return 0;
}
结果:
chararcters total in sentence.
spaces = 3
total = 31
*如果遇到的字符不是点,那是不是空格呢,前面触发点+1,后面触发空格+1
1:if else语句
对比以下两个程序,感受数据提升
1)使用++ch,不会丢失char
#include <iostream>int main(void)
{using namespace std;char ch;cout << "Type ,and I shall repeat.\n";cin.get(ch);while (ch!='.'){if(ch == '\n')cout << ch;else cout << ++ch;cin.get(ch);}cout << endl;return 0;
}
结果:
Type ,and I shall repeat.
a
b
c
d
.
2)使用ch + 1,变成了数据类型提升,输出就是数字
#include <iostream>int main(void)
{using namespace std;char ch;cout << "Type ,and I shall repeat.\n";cin.get(ch);while (ch!='.'){if(ch == '\n')cout << ch;else cout << ch + 1;cin.get(ch);}cout << endl;return 0;
}
结果:
Type ,and I shall repeat.
c
100
d
101
2:格式化if else语句
别忘了{}
3:if else if else结构
看如下程序:
#include <iostream>int main(void)
{using namespace std;const int Fave = 27;int n;cout << "Enter number in the range 1-100 to find your favorite number : ";do{cin >> n;//先输入if(n < Fave)cout << "Too low ,guess again!" << endl;else if(n > Fave)cout << "Too high ,guess again!" << endl; else cout << Fave << " is the right number." << endl;} while (n != Fave);//如果不是Fave呢return 0;
}
结果如下:
Enter number in the range 1-100 to find your favorite number : 24
Too low ,guess again!
27
27 is the right number.
*相等运算符最好这样声明!
if(3 == myNumber)
就算少写了等号,也不会报错
二、逻辑表达式
逻辑运算符的优先级比关系运算符低
1:逻辑OR运算符:||
满足其一就行
C++规定,||运算符是一个顺序点,如果左侧的表达式为true,则C++不会去判定右侧表达式
看下程序:
#include <iostream>int main(void)
{using namespace std;cout << "This program may reformat your hard disk \n""and destroy all your data. \n""do you wish to continue?<y/n> ";char ch;cin >> ch;if(ch=='y' || ch == 'Y')cout << "You were warned!" << endl;else if(ch == 'n' || ch == 'N')cout << "A wise choise.." << endl;else cout << "That wasn't a y or n!" << endl;return 0;
}
2:逻辑AND运算符:&&
必须同时满足
如果左侧为false,则整个逻辑表达式必定为false,在这种情况下,C++不会对右侧进行判定了
看下程序:
#include <iostream>const int ArSize = 6;int main(void)
{using namespace std;float value[ArSize];float temp;int i;cout << "Enter six numbers and campare with your level:" << endl;cout << "Terminate condition: when you make 6 numbers or enter a nagative number" << endl;cout << "First value: ";cin >>temp;while (i < ArSize && temp >= 0){value[i] = temp;++i;if (i < ArSize){cout << "Next value:";cin >> temp;}}if (i == 0){cout << "No date--byte." << endl;}else{cout << "Enter your level: ";float level;cin >> level;int count = 0;for (int j = 0; j < i; j++){if (value[j] > level)count++;}cout << count << " numbers are bigger than your level" << endl;}return 0;
}
结果如下:
Enter six numbers and campare with your level:
Terminate condition: when you make 6 numbers or enter a nagative number
First value: 12
Next value:55
Next value:5
Next value:6
Next value:5
Next value:43
Enter your level: 10
3 numbers are bigger than your level
*程序说明
1)声明一个浮点型的数组,大小为6,初始化一个浮点型的数,用于捕获和存放
2)while循环就是为了提醒和存放数据
3)存放完成后,后面定义一个float标准进行比较
4)出现负数直接返回
3:用&&来设置取值范围
使用if (age >17 && age < 35)而不是if (17 < age < 35) !
看下例:
#include <iostream>int main(void)
{using namespace std;const char *qualify[] = {"Perfect","Great","Good","Just soso","failed"};int score;int index;cout << "Enter your score: ";cin >> score;if(score >= 90 && score <= 100){index = 0;}else if (score >= 80 && score < 90){index = 1;}else if(score >= 70 && score < 80){index = 2;}else if(score >= 60 && score < 70){index = 3;}elseindex = 4;cout << "Your qualify: " << qualify[index] << endl;return 0;
}
结果:
Enter your score: 96
Your qualify: Perfect
*用了index,这样就减少了代码量,不然每一行都输出你的成绩,比较麻烦
4:逻辑NOT运算符:!
!运算符的优先级高于所有的关系运算符和算术运算符的,记得加()。
看代码
#include <iostream>
#include <climits>bool is_int(double x);//记得声明函数啊,不然没法用哦int main(void)
{using namespace std;double num;cout << "Enter an interger value: ";cin >> num;while (!is_int(num))//如果不是int,就重新输入{cout << "Out of range, please enter again: ";cin >> num;}int value = int(num);//否则就输出强制转换为int类型的numbercout << "You have enter an interger: " << value << endl;return 0;
}bool is_int(double x) //定义了一个bool类型的判断是否是int的函数,参数是double,返回值是bool
{if(x<= INT_MAX && x >= INT_MIN) //如果输入在int的最大最小范围之内,就确定是intreturn true;elsereturn false;
}
结果:
Enter an interger value: 10000000000000
Out of range, please enter again: 10
You have enter an interger: 10
*
1)记得引用函数
2)记得类型转换
5:逻辑运算符细节
&&运算符的优先级高于||
三、字符函数库cctype
这个头文件还是很好用的,能判断你输入的是不是字母,数组,控制符,小写,大写,标点,十六进制等。。
写个代码:
#include <iostream>
#include <cctype>//这就是很好用的那个玩意儿int main(void)
{using namespace std;int whitespace = 0;int digits = 0;int chars = 0;int punch = 0;int others = 0;char ch;cout << "Enter text for analysis , and @ to terminate the input." << endl;cin.get(ch);while (ch != '@'){if(isalpha(ch))chars++;else if(isspace(ch))whitespace++;else if(isdigit(ch))digits++;else if(ispunct(ch))punch++;elseothers++;cin.get(ch);}cout << chars << " letters," << whitespace << " whitespaces," << digits << " digits," << punch << " punchs," << others << " others." << endl;return 0;
}
结果:
Enter text for analysis , and @ to terminate the input.
My dinner with Andre, scheduled for 2013.
@
29 letters,7 whitespaces,4 digits,2 punchs,0 others.
*就是调用了cctype头文件,能够判断大小写字母数字字符空格什么的
四、?:运算符(条件运算符)
C++ 有一个长被用来代替if else语句的运算符,这个运算符被称为条件运算符(?:),它是C++中唯一一个需要3个操作数的运算符。通用格式如下:
expression1 ? expression2 : expression3
如果1为true,则整个条件表达式的值为2,否则就是3
常见用法,见以下代码:
#include <iostream>int main(void)
{using namespace std;int a,b;int c;cout << "Enter two intergers: \n";cin >> a >> b;c = a > b ? a : b;cout << c;return 0;
}
结果:
Enter two intergers:
10
20
20
对于比较复杂的条件语句,用if else更好,如果指示简单的关系表达式,用?:(条件表达式)更方便。
五、Switch语句
Switch语句更能够容易从大型列表中进行选择
Switch (integer - expression)
{
case 1 :statement
case 2:statement
...
default : statement
}
程序不会在执行到下一个case处自动停止,要让程序执行完一组特定语句后停止,必须使用break语句,这将导致程序switch后面的语句处执行!
以下程序会演示switch和break
#include <iostream>using namespace std;void showmenu(void);
void report(void);
void comfort(void);int main(void)
{showmenu();int choice;cin >> choice;while (choice != 5){switch (choice){case 1:cout << "\a\n";break;case 2:report();break;case 3:cout << "boss was in all day.\n";break;case 4:comfort();break;default:cout << "That's not a choice\n";break;}showmenu();cin >> choice;}cout << "Bye!\n";return 0;
}
void showmenu(void)
{cout << "Please enter 1,2,3,4,5 as your choice:" << endl;cout << "1) alarm 2) report" << endl;cout << "3) alibi 3) comfort" << endl;cout << "5) quit" << endl;
}
void report(void)
{cout << "It has been an excellet week for bussiness.\n";
}
void comfort(void)
{cout << "in the industry. The board of directors think\n";
}
运行结果如下:
Please enter 1,2,3,4,5 as your choice:
1) alarm 2) report
3) alibi 3) comfort
5) quit
1
Please enter 1,2,3,4,5 as your choice:
1) alarm 2) report
3) alibi 3) comfort
5) quit
2
It has been an excellet week for bussiness.
Please enter 1,2,3,4,5 as your choice:
1) alarm 2) report
3) alibi 3) comfort
5) quit
3
boss was in all day.
Please enter 1,2,3,4,5 as your choice:
1) alarm 2) report
3) alibi 3) comfort
5) quit
4
in the industry. The board of directors think
Please enter 1,2,3,4,5 as your choice:
1) alarm 2) report
3) alibi 3) comfort
5) quit
5
Bye!
*
1)定义了三个没有参数没有返回值的方法
2)switch 记得要加break
3)函数记得引用
如果没有break,它就会一直执行下去,有时候其实也有用
1:将枚举量作为标签
定义一个枚举,然后在switch里面直接用就行了,见下面程序
#include <iostream>enum {red,orange,yellow,green,blue,violet,indigo};//定义枚举量int main(void)
{using namespace std;int code;cout << "Enter color code(0~6):";cin >> code;while(code >= red && code <= indigo){switch (code){case red:cout << "You choose red!" << endl;break;case orange:cout << "You choose orange!" << endl;break;case yellow:cout << "You choose yellow!" << endl;break;case green:cout << "You choose red!" << endl;break;case blue:cout << "You choose blue!" << endl;break;case violet:cout << "You choose violet!" << endl;break;case indigo:cout << "You choose indogo!" << endl;break;}cout << "Enter color code(0~6):";cin >> code;}cout << "Bye!" << endl;return 0;
}
结果:
Enter color code(0~6):0
You choose red!
Enter color code(0~6):1
You choose orange!
Enter color code(0~6):2
You choose yellow!
Enter color code(0~6):3
You choose red!
Enter color code(0~6):4
You choose blue!
Enter color code(0~6):5
You choose violet!
Enter color code(0~6):6
You choose indogo!
Enter color code(0~6):8
Bye!
*里面不用default了,因为就那么点变量,while跳出来以后再进行选择
2:switch和if else
if lese更适合处理取值范围
switch语句每个标签都是单独的值,必须是整数或者char,不能判断浮点型,更不能判断取值范围了
六、break和continue语句
break和continue都能使程序跳过部分代码
但是break是跳过当前循环,continue是跳过循环体剩下的语句,直接进行下一轮循环
下面的程序是演示两条语句是如何工作的
#include <iostream>const int ArSize = 80;int main(void)
{using namespace std;char line[ArSize];int spaces = 0;cout << "Enter a line of text:" << endl;cin.get(line,ArSize);cout << "Complete line: " << line << endl;for(int i = 0; line[i] != '\0'; i++){cout << line[i];if(line[i]=='.')break; //如果找到句号,直接就跳出循环if(line[i]!=' ')continue;//如果没有找到空格,直接跳出循环spaces++;} cout << endl;cout << "Spaces = " << spaces << endl;return 0;
}
结果:
Enter a line of text:
hello world.good morning
Complete line: hello world.good morning
hello world.
Spaces = 1
*
1)如果执行了continue,后面的space++就不执行了,直接跳到i++部分
2)比如说,我们第一个字符是h,对于h,先会打印出来,然后到if,它不是句号,所以不会break,紧接着到了下一个if语句,它如果不是空格,那么就会执行continue而跳过space++,直接到下一个i。
七、读取数字的循环
当我们使用cin进行输入数字时,如果不小心输入了字母,单词,就会发生如下情况:
·n值保持不变
·不匹配的输出留在队列中
·cin对象中的一个错误标记被设置
·对cin方法调用返回false
那如何解决呢??
看下例直接:
#include <iostream>using namespace std;int main(void)
{int num1,num2;cout << "First num: ";cin >> num1;cin.clear();//reset inputwhile (cin.get()!='\n');cout << "Second num: ";cin >> num2;cout << "num1 = " << num1 << ", num2 = " << num2 << endl;return 0;
}
结果:
First num: xyz
Second num: 2
num1 = 0, num2 = 2
*
1)使用cin.clear()方法来重置输入
2)把留在队列的错误输入值使用while(cin.get()!='\n')来重置
再看个捕鱼的例子:
#include <iostream>const int Max = 5;
using namespace std;int main(void)
{double fish[Max];cout << "Please enter the weight of your fish:" << endl;cout << "You may enter up to " << Max << " fish <q> to terminate." << endl;cout << "fish #1 \n";int i = 0;while (i < Max && cin >> fish[i]) //第二个条件的意思是你输入的必须要满足它是重量,如果是其他类型直接跳出{if(++i < Max)cout << "fish # " << i+1 << ": " << endl;}double total = 0.0;for (int j = 0; j < i; j++) //这个意思是,你录入多少条,就输出多少条,并不是Max{total += fish[j];//这里是j不是i}cout << "total =" << total << endl;if (i == 0){cout << "No fish" << endl;}elsecout << "Average weight of " << i << " fish: " << total / i << endl;return 0;
}
结果:
Please enter the weight of your fish:
You may enter up to 5 fish <q> to terminate.
fish #1
2.3
fish # 2:
3.2
fish # 3:
4.4
fish # 4:
1.2
fish # 5:
3.3
total =14.4
Average weight of 5 fish: 2.88
*
那如果输入错误,应该采取哪种措施呢?
·重置cin以接受新的输入
·删除无效输入
·提示用户输入新的输入
那我们看下面的程序:读取高尔夫得分,并计算平均得分,如果输入错误,会提示输入错误,重新输入。
#include <iostream>const int Max = 5;
using namespace std;int main(void)
{int golf[Max];cout << "Please enter your golf scores:\n";cout << "You must enter " << Max << " rounds.\n" ;int i;for (i = 0; i < Max; i++){cout << "Round" << i+1 << ":" << endl;while(!(cin >> golf[i]))//这里取反就是说,输入的不是数字,而是其他类型{cin.clear();while(cin.get() != '\n') //删除用户的信息,消耗掉回车前的信息,用get()continue;//跳出while循环cout << "Please enter a number : \n";}}double total = 0;for (i= 0; i < Max; i++){total += golf[i];}cout << "The average score is : " << total / Max << "." << endl; return 0;
}
结果如下:
Please enter your golf scores:
You must enter 5 rounds.
Round1:
22
Round2:
33
Round3:
ad
Please enter a number :
22
Round4:
dd
Please enter a number :
11
Round5:
22
The average score is : 22.
*注意while那块的continue,如果不加的话,会输出三遍“please enter a number”
八、简单文件输入/输出
不能总要通过键盘输入,假设从文件导入数据会更好,这里先介绍简单的文本文件I/O
1:文本I/O和文本文件
使用cin进行输入时,程序将输入视为一系列的字节,其中每个字节都被解释为字符编码。不管目标数据类型是什么,输入一开始都是字符数据——文本数据,然后cin对象负责将文本转换为其他其他类型。我们来看下是如何进行的。
假设有如下示例输入行:
38.5 19.2
首先来看使用char数据类型的情况:
char ch;
cin >> ch;
输入行中的第一个字符被赋给ch,第一个字符是数字3,其二进制编码被存储在变量ch中。
输入和目标变量都是字符,因此不需要进行转换。注意这里存储的不是数值3,而是3的编码
对于int类型:
int n;
cin >> n;
cin会不断读取,直到遇到非数字字符
也就是说,它读取3和8,这样句点将称为输入队列中的下一个字符。cin通过计算发现,这两个字符对应数值38,因此将38的二进制编码复制到变量n中
对于double类型:
double x;
cin >> x;
cin不断读取,直到遇到第一个不属于浮点数的字符
cin读取3,8,句号和5,使得空格称为输入队列中的下一个字符,所以会把38.5的二进制编码复制到x中
对于char数组类型
char word[50];
cin >> wordk;
cin将不断读取,直到遇到空白字符
所以会读取3、8、点和5,使得空格称为输入队列中的下一个字符。存储的是'3','8','.'
然后cin将这4个字符编码存储到数组word中,并在末尾加上一个
最后看另一种char数组存储情况
char word[50]
cin.getline(word,50);
这种情况下,cin将一直读取,直到遇到换行符
所有字符都会被存储到数组word中,并在末尾加上一个空字符,换行符被丢弃,输入队列中的下一个字符是下一行中的第一个字符,这里不需要进行任何转换(存进去的都是字符)
本章讨论的文件IO相当于控制台IO,因此仅适用于文本文件
2:写入到文本文件中
再复习以下cout的东西
·必须包含头文件iostream
·头文件iostream定义了一个用于处理输出的ostream类
·头文件iostream声明了一个名为cout的ostream变量
·必须有命名空间std
·结合cout和运算符 <<来显示各种信息
文件输出和它非常类似
·必须包含头文件fstream
·头文件fstream定义了一个用于处理输出的ofstream类
·需要声明一个或多个ofstream对象,并以自己喜欢的方式对其进行命名,条件是遵守常用的命名规则
·必须使用命名空间std
·需要将ofstream对象和文件关联起来,为此,方法之一是使用open()方法
·使用完了后,应该使用close()关闭
·可以结合使用ofstream对象和运算符<<来输出各种类型的数据
下列代码演示了这种方法:
#include <iostream>
#include <fstream>using namespace std;int main(void)
{char automobile[50];int year;double a_price;double d_price;ofstream outFile;//1.创建一个输出文件流的对象outFile.open("carinfo.txt"); //2.使用outfile创建文本文件cout << "Enter the make and model of automobile: ";cin.getline(automobile,50);cout << "Enter the model year: ";cin >> year;cout << "Enter the orignal asking price: ";cin >> a_price;d_price = a_price * 0.913;cout << "Make and model: " << automobile << endl;cout << "Year: " << year << endl;cout << "Was asking: " << a_price << endl;cout << "Now asking: " << d_price << endl;outFile << "Make and model: " << automobile << endl;outFile << "Year : " << year << endl;outFile << "Was asking: " << a_price << endl;outFile << "Now asking: " << d_price << endl;return 0;
}
*
1)文件流中并没有预先创建好类似cin和cout之类的对象,需要自己创建,它由ofstream和ifstream组成
2)ofstream创建,然后调用open方法
3)调用完了以后,使用cout类似的方法,使用outFile方法就行了
结果如下:
Enter the make and model of automobile: Flitz Perky
Enter the model year: 2009
Enter the orignal asking price: 13500
Make and model: Flitz Perky
Year: 2009
Was asking: 13500
Now asking: 12325.5
同时生成了carinfo的文本文件
但是这里的Was asking里面只显示了一位,如何能让他显示小数点后两位呢?
下面使用fixed修正:
#include <iostream>
#include <fstream>//文件流中并没有预先创建好类似cin和cout之类的对象,需要自己创建,它由ofstream和ifstreamusing namespace std;int main(void)
{char automobile[50];int year;double a_price;double d_price;ofstream outFile;//1.创建一个输出文件流的对象outFile.open("carinfo.txt"); //2.使用outfile创建文本文件cout << "Enter the make and model of automobile: ";cin.getline(automobile,50);cout << "Enter the model year: ";cin >> year;cout << "Enter the orignal asking price: ";cin >> a_price;d_price = a_price * 0.913;cout << "Make and model: " << automobile << endl;cout << "Year: " << year << endl;cout << "Was asking: " << a_price << endl;cout << "Now asking: " << d_price << endl;outFile << "Make and model: " << automobile << endl;outFile << "Year : " << year << endl;outFile << "Was asking: " << a_price << endl;outFile << "Now asking: " << d_price << endl;cout << fixed;cout.precision(2);//显示两位cout.setf(ios_base::showpoint);cout << "Make and model: " << automobile << endl;cout << "Year: " << year << endl;cout << "Was asking: " << a_price << endl;cout << "Now asking: " << d_price << endl;outFile << fixed;outFile.precision(2);//显示两位outFile.setf(ios_base::showpoint);outFile << "Make and model: " << automobile << endl;outFile << "Year: " << year << endl;outFile << "Was asking: " << a_price << endl;outFile << "Now asking: " << d_price << endl;return 0;
}
显示如下:
Enter the make and model of automobile: Nissan
Enter the model year: 2011
Enter the orignal asking price: 200000
Make and model: Nissan
Year: 2011
Was asking: 200000
Now asking: 182600
Make and model: Nissan
Year: 2011
Was asking: 200000.00
Now asking: 182600.00
再来看文本文件:
从文本内容可以看得出来,并不是追加文件,而是把原来的内容删除了,重新写入
3:读取文本文件
再跟cin对比以下:
文本输入:
·必须包含头文件iostream
·头文件iostream定义一个用于处理输入的istream类
·头文件iostream声明一个名为cin的istream变量
·必须写出命名空间std
·结合>>来读取各种类型数据
·使用cin的方法get()和getling()方法读取一行
·可以结合使用cin和eof()、fail()方法来判断输入是否成功
·对象cin本身被用作测试条件时,如果最后一个读取操作成功,会被转换为Bool的true。
文件输入:
·头文件包含fstream
·头文件fstream定义一个用于处理输入的ifstream类
·需要声明一个或多个ifstream变量,并命名
·指出命名空间std
·需要将ifstream对象和文件关联起来,方法之一是open()方法
·使用完了用close()关闭
·结合ifstream对象和运算符>>读取各种数据类型
·可以使用get()或getline()方法
·可以结合使用cin和eof()、fail()方法来判断输入是否成功
·对象ifstream本身被用作测试条件时,如果最后一个读取操作成功,会被转换为Bool的true。
代码如下:
#include <iostream>
#include <fstream>
#include <cstdlib>const int SIZE = 60;using namespace std;int main(void)
{char filename[SIZE];ifstream inFile;cout << "Enter name of data file: ";cin.getline(filename,SIZE);inFile.open(filename);if(!inFile.is_open())//如果不能打开就打开失败,退出{cout << "could not open the file " << filename << endl;cout << "Program terminating." << endl;exit(EXIT_FAILURE);}cout << "Success open the txt file." << endl;//记得别忘了后缀txtdouble value;double sum = 0.0;int count = 0;inFile >> value;while (inFile.good())//如果从文件当中能读取数据,一直到读取不到,就退出循环{++count;sum += value;inFile >> value;}if (inFile.eof())//end of file,读取到文件末尾,判断文末必须有{cout << "End of file!" << endl;}else if(inFile.fail())//如果读取失败cout << "Input terminater by data mismachted." << endl;if(count == 0)cout << "No data processed." << endl;else{cout << "Items read: " << count << endl;cout << "Sum = " << sum << endl;cout << "Average: " << sum / count << endl;}inFile.close();return 0;
}
*
1)声明fstream头文件,然后使用ifstream类,创建一个对象,然后调用open()方法
2)判断是否打开,使用is_open()方法,如果不能打开就使用exit()方法,它位于cstrlib头文件中
3)使用while循环使用good()方法,看能否从文件中读取数据
4)判断是否到文件尾,使用eof方法
5)读取失败使用inFail中的fail()方法
6)如果数量太少的话,比如时0,就返回没有值
运行结果:
Enter name of data file: 6-19file.txt
Success open the txt file.
End of file!
Items read: 11
Sum = 186.9
Average: 16.9909
九、复习题和编程练习
1:复习题
1:
同样进入while循环
第一种执行完if语句之后,会重新检测一遍ch中的字符
而第二种执行完if语句后,会把其中的空格部分都去掉,避免了重复检测
2:在如下代码中,如果用ch+1替换++ch有什么变化?
解:我们的输入是字符,主要部分的目的是把字符向前一位
如果++ch变成ch+1,那就会变成数字,而不是字符
3:请阅读以下代码,假设输入如下:
Hi!
Send $10 or $20 now!
则输出将是什么?
定义char型和整型ct1和ct2,然后进入while循环
如果输入的字符不是’$‘,那么就进入循环,打印出这个字符,然后ct2++
后面的if语句里面是赋值,把$给了ch,所以永远为真,ct2++,然后输出$,就往复循环,直到while的条件不满足,即碰到$就停止,然后输出ct1,ct2
H$i$!$
$S$e$n$d$ $ ,这时候碰到了$,停止while循环,跳出,打印ch1,ch2
此时输出ch1和ch2=9;
4:创建表示下述条件的逻辑表达式:
a:weight大于或等于115,但是小于125
weight >=115 && weight < 125;
b:ch为q或Q
ch ='q' || 'Q';
c:x为偶数,但不是26
(x%2)=0 && (x != 26),注意偶数的表达方式
d:x为偶数,但不是26倍数
(x%2)= 0 && (x % 26 != 0),注意不是倍数的表达方式
e:donation为1000-2000或guest为1
(donation >= 1000 && donation <= 2000) || (guest == 1)
f:ch是小写字母或大写字母(假设小写字母和大写字母是依次编码的,但在大小写之间编码不是连续的)
(ch >= a" && ch <= z") || (ch >= A" && ch <= Z")
5:在英语中,“i will not speak”的意思和"i will speak"相同,在C++中,!!x和 x是否相同呢?
如果x是bool类型是OK的
如果x是int,那么!x就true,再取反变成false,然后变成true,所以不行
6:创建一个条件表达式,其值为变量的绝对值。也是说,如果变量x为正,则表达式的值为x,但是如果x为负,则表达式的值为-x——这是一个正值
int x;
if(x >= 0)cout << x;
elsecout << -x;
但是推荐用条件表达式,对于这种比较简单的判断式:
(x >=0) : x ? -x
7:用switch语句改写下面代码:
switch (ch)
{
case 'A':a_grade++;break;
case 'B':b_grade++;break;
case 'C':c_grade++;break;
case 'D':d_grade++;break;
default:break;
}
8:对于如下程序,与使用数字相比,使用字符(如a或c),表示菜单选项和case标签有何优势呢?(比如用户输入q或5)
#include <iostream>using namespace std;int main(void)
{showmenu();int choice;cin >> choice;while (choice != 5){switch (choice){case 1:cout << "\a\n";break;case 2:report();break;case 3:cout << "boss was in all day.\n";break;case 4:comfort();break;default:cout << "That's not a choice\n";break;}
1)choice定义为int类型,那么你输入12345,其实是先把字符12345转化成int类型存放到choice里面
然后choice再和12345对比,如果你此时输入的是整型,那没有什么问题,但是如果输入的是字符,那么程序就会出问题
2)但是如果定义为char型,那么无论输入的是数字还是字母,都不会有问题
如下:
char choice;cin >> choice;while (choice != '5')//修改为字符5{switch (choice){case '1':cout << "\a\n";break;case '2':report();break;case '3':cout << "boss was in all day.\n";break;case '4':comfort();break;default:cout << "That's not a choice\n";break;}
如果是这样的,输入字符也不会有任何问题
9:看如下代码:
请重写该代码,不要使用break和continue语句
int line = 0;
char ch;
while(cin.get(ch) && ch != 'Q')
{
if(ch == '\n')
line++;
}
2:编程练习
1:编写一个小程序,读取键盘输入,直到遇到@符号为止,并回显(数字除外),同时将大写字符转换为小写。将小写字符转换为大写(cctype函数)
#include <iostream>
#include <cctype>using namespace std;int main(void)
{char ch;cout << "Please enter a character: ";cin >> ch;if (ch == '@'){cout << ch << endl;}else if (isdigit(ch))cin >> ch;else if(islower(ch)){ch = toupper(ch);}else {ch = tolower(ch);}cout << ch;cin >> ch;return 0;
}
*
1)cctype头文件
2)isdigit()判断数组,islower()判断小写,issupper()判断大写
3)tolower()大转小,toupper()小转大
2:编写一个程序,最多将10个donation值读入到一个double数组中,程序遇到非数字输入时将结束输入,并报告这些数字的平均值及数组中有多少个数大于平均值。
#include <iostream>
#include <array>using namespace std;
const int SIZE =10;int main(void)
{array<double,SIZE> donation;double input;int count = 0;double sum = 0.0;double average;int bigger;cout << "Please enter the double numerial: ";while ((cin >> input))donation[count++] = input;if(count == 10)break;cout << "Please enter the double numerial: "; }for (int i = 0; i < count; i++){sum += donation[i];}average = sum / count;for (int i = 0; i < count; i++){if (donation[i] > average){bigger++;}}cout << "Average = " << average << "," << bigger << " numbers are bigger than averager. " << endl;return 0;
}
结果:
Please enter the double numerial: 12.5
Please enter the double numerial: 12.1
Please enter the double numerial: a
Average = 12.3,1 numbers are bigger than averager.
*
注意判断是不是字母那块,不用isdigit判断,其实光写cin >> input就够了,因为如果你输入的东西放不到double里面去,说明它不是数字
3:编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。然后用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。
然后该程序使用一条switch语句,根据用户的选择执行一个简单的操作。该程序运行如下:
#include <iostream>using namespace std;
void showmenu(void);int main(void)
{char ch;showmenu();cin >> ch;//也可cin.get()while (ch != 'c' && ch!= 'p' && ch != 't' && ch!='g'){cin.get();//消耗上面的回车字符cout << "Please enter a character: c,p,t,g: " ;cin >> ch;}switch (ch){case 'c':break;case 'p': break;case 't': break;case 'g': cout << "A map is a tree." << endl;default:break;}return 0;
}
void showmenu(void)//菜单函数
{cout << "Please enter one of the following choices: " << endl;cout << "c) carnivore\t\t p)pianist" << endl;cout << "t) tree\t\t\t g) game" << endl;
}
结果如下:
Please enter one of the following choices:
c) carnivore p)pianist
t) tree g) game
a
Please enter a character: c,p,t,g: b
Please enter a character: c,p,t,g: g
A map is a tree.
*
1)一个选择提示,调用menu函数
2)switch语句,选择操作
3)捕获输入
4:加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解它。
请编写一个程序,可以使用真实姓名,头衔,秘密姓名或成员偏好来列出成员。请使用以下结构:
该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值,另外,使用一个循环,让用户在下面的选项中进行选择:
注意:"display by the preference"并不意味着显示成员偏好,而是意味着根据成员偏好来列出成员。
例如:如果偏好为1,则选择d将显示程序员的头衔。该程序运行情况如下:
程序如下:
#include <iostream>using namespace std;const int strsize = 20;
const int usersize = 4;void showmenu(void);void print_by_fullname(void);
void print_by_title(void);
void print_by_bopname(void);
void print_by_preference(void);struct bop
{char fullname[strsize];char title[strsize];char bopname[strsize];int preference;
};bop user[usersize] = {{"Rick","Level_A","RR",0},{"Jack","Lever_B","JJ",1},{"Micheal","Lever_C","MM",2},{"Rose","Lever_D","RR",3}};int main(void)
{showmenu();char input;cin >> input;while (input!= 'q'){switch (input){case 'a':print_by_fullname();break;case 'b':print_by_title();break;case 'c':print_by_bopname();break;case 'd':print_by_preference();break;default:cout << "Please enter character a,b,c,d,q:" << endl; //把判断条件放到default也是不错的}cin.get();cout << "Next input: ";cin >> input;}cout << "Bye!" << endl;return 0;
}
void showmenu(void) //菜单函数
{cout << "Benevolent Order of Programmers Report " << endl;cout << "a) display by name\t\t b)display by title" << endl;cout << "c) display by bopname\t\t\t g) display by preference" << endl;cout << "q) quit " << endl;
}void print_by_fullname(void)
{for (int i = 0; i < usersize; i++){cout << user[i].fullname << endl;}
}void print_by_title(void)
{for (int i = 0; i < usersize; i++){cout << user[i].title << endl;}
}void print_by_bopname(void)
{for (int i = 0; i < usersize; i++){cout << user[i].bopname << endl;}
}void print_by_preference(void)
{for(int i = 0; i < usersize; i++){switch (user[i].preference){ case 0:cout << user[i].fullname << endl;break;case 1:cout << user[i].title << endl;break;case 2:cout << user[i].bopname << endl;break;default:break;}}
}
结果:
Benevolent Order of Programmers Report
a) display by name b)display by title
c) display by bopname g) display by preference
q) quit
a
Rick
Jack
Micheal
Rose
Next input: b
Level_A
Lever_B
Lever_C
Lever_D
Next input: c
RR
JJ
MM
RR
Next input: d
0
1
2
3
Next input: q
Bye!
*
1)在switch的时候把判断条件放到default也是不错的,这样就不用在while中写太多
2)注意main定义的数组在main外部无法访问的,一定要记住
3)创建结构,创建结构数组,创建while-switch循环,创建外部函数,访问完了要消耗
5:在Neutronia王国,货币的单位是tvarp,收入所得税计算方式如下:
5000 trarps:不收税
5001~15000 tvarps: 10%
15001~35000 tvarps: 15%
35000 tvarps+: 20%
请编写一个语句,使用循环来要求用户输入收入,并报告所得税,输入负数或者非数字结束循环。
例如输入38000,所得税5000×0.00+10000×0.10+20000×0.15+3000×0.20,即4600.
程序:
C++入门——Day5_分支语句和逻辑运算符相关推荐
- C++ Primer Plus学习(六)——分支语句和逻辑运算符
分支语句和逻辑运算符 if语句 逻辑表达式 字符函数库cctype ?: 运算符 switch语句 break和continue语句 读取数字的循环 文件输入\输出 写入到文本文件中 读取文本文件 i ...
- C++ Primer Plus(嵌入式公开课)---第5,6章 循环和关系表达式 分支语句和逻辑运算符
20220222 C++ Primer Plus - 第五.六章 附录: 1.ASCII码字符对照表 2.C++ 运算符优先级 第1-3章 第4章 复合类型 第5章 循环和关系表达式 5.1 for循 ...
- 每日十问6c++-分支语句和逻辑运算符
每日十问6c+±分支语句和逻辑运算符 1.请看下面两个计算空格和换行符数目的代码片段.//版本 1 while(cin.getch()) //在遇到 EOF 时退出 if(ch =='') space ...
- Python入门(7)——分支语句与循环语句
Python代码块 首先说明一下Python代码块的问题.Python有着严格的代码缩进要求,对于有C++.Java等编程经验的人来说,区分代码块是以花括号{}形式进行划分的.但对于Python来说, ...
- 【C++ Primer Plus】第6章 分支语句和逻辑运算符
6.1 if 语句 if 语法: if (test-condition) statement if 测试条件将被强制转换为bool值,因此0将被转换为false,非零为true. 6.2 if els ...
- C++PrimerPlus 第六章 分支语句和逻辑运算符(复习题)
1.请看下面两个计算空格和换行符数目的代码片段: //Version 1 while(cin.get(ch)) //quit on eof {if(ch == ' ')spaces++;if(ch = ...
- Linux Shell脚本入门教程系列之(十三)Shell分支语句case … esac教程
本文是Linux Shell脚本系列教程的第(十三)篇,更多Linux Shell教程请看:Linux Shell脚本系列教程 上一篇之 后,分支语句非常实用,基本上高级语言都支持分支语句(pytho ...
- python分支判断语句_python 分支语句 等值判断 逻辑运算符
# 分支语句 age = 233 if age < 18: print('您还未满18岁,禁止入内') elif age > 18 and age < 60: print(" ...
- java教程分支_Java小白入门教程(5)——分支语句
原标题:Java小白入门教程(5)--分支语句 提纲: 1.程序的流程结构 2.选择结构 3.if语句 4.switch-case语句 5.作业 一.程序的流程结构 程序的流程结构 程序的流程结构: ...
最新文章
- 大型分布式网站架构技术总结
- 输入两个整数序列。其中一个序列表示栈的push顺序, 判断另一个序列有没有可能是对应的pop顺序。
- 如何通过github提升自己
- bitmap xml大小 安卓_一张壁纸让安卓用户手机系统崩溃,包括三星、小米、一加等...
- 大型WEB架构概况(笔记整理)一
- 用友邮件撤回怎么操作_用户体验原则——“操作可控”
- 把github转至gitee
- java线程如何继承,java多线程(一)之继承Thread类
- 动手写个数字输入框2:起手式——拦截非法字符
- spring源码解析(一)---占位符解析替换
- C C++如何获取当前系统时间
- 怎么把汉字转换成URL编码
- 读 Robert C. Solomon 之《哲学导论》
- 计算机硬盘中有许多碎片,电脑磁盘碎片整理有什么用(需要经常清理吗)
- 拼多多顶级佣金助手-微信群自动发单
- iso文件连接ftp服务器,使用本机文件浏览器访问FTP服务器 | MOS86
- spfa判断负环( 负环判定 + spfa )
- Poser 11基本使用
- 【转】创业公司如何公平分配股权
- 2021重庆科技学院调剂复试真题总结
热门文章
- 怎么设置计算机硬盘密码,移动硬盘如何设置密码【操作步骤】
- 我的理想作文400字计算机,我的理想作文400字5篇
- 前端实现导入PPT在线编辑
- Pandas中透视表和交叉表
- parzen窗估计如何进行结果分析_Parzen窗方法的分析和研讨
- 前端实现GIF图片压缩上传
- 第三课:布尔逻辑与逻辑门
- android 选择相册拍照图片 仿gridview九宫格 recycleview九宫格图片(可拖拽)
- 华为交换机端口配置删除_华为交换机配置_华为交换机怎么清除端口下所有配置?...
- 高等数学——常用结论(3)