[分支语句和逻辑运算符]——C++ Prime Plus-ch6

本文详细介绍了C++中的分支语句,包括if、逻辑运算符、switch及条件运算符的使用。讲解了如何利用if-else进行条件判断,逻辑运算符的短路特性,以及switch在处理多选项时的优势。此外,还探讨了字符函数库cctype的使用,条件运算符的简洁表达,以及break和continue在循环控制中的作用。文章还涉及到简单的文件输入输出操作。
摘要由CSDN通过智能技术生成

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值