【C++基础语法】04 C++ 多分支 if ... else if ... else 、switch 及逻辑表达式

C++ 双分支 甲乙两个人在公园相遇,甲说我今年n岁了(n是一个两位的整数,个位和十位不相等),乙说,太巧了,你的年龄倒过来,就是我的年龄,请问两个人谁的年龄更大,请输出那个更大的年龄?请从键盘读入一个三位整数,判断这个三位整数是否是对称数(对称数指的是,这个数正过来和倒过来是同一个数,比如:121、686、808等数都是对称数),如果是对称数,则输出“Y”,否则输出“N”。小明去冷饮店买冰激凌,如果买10个以上或者10个,2元/个,10个以下,2.2元/个,请从键盘读入小明的购买数量,计算小明应付的价格! 阅读详情

再次说明,本专栏文章采用最少必要知识原则,只讲解必要知识,让青少年,先上手编程,再上道。

文章采用更简单易懂的文字,不涉及很多的专有名词,部分举例有失精准。一切为了开始入门编程。

请先复习上文 - 重点回顾 - 部分内容。

多分支 if … else if … else

多分支语句,是对同一个条件表达式的的不同结果,分别执行不同的代码块。({ } 括起来的就是代码块)

举例:判断一个整数,是正数、负数、还是 0。判定整数和 0 的关系

  • 若是大于 0,输出 positive
  • 若是小于 0,输出 negative
  • 若是等于 0,输出 zero

点我,在线编程试一下👇

#include <iostream>
using namespace std;

int main(){

	int n;
	cin >> n;

	if(n > 0) {
		cout << "positive" << endl;
	} else if(n < 0) {
		cout << "negative" << endl;
	} else if(n == 0) {
		cout << "zero" << endl;
	}

	return 0;
}

其中,最后一个 else if(n == 0),可直接写成 else ,这没有任何问题,但不建议,我一般写成 else if(n == 0) ,可读性会更加好。else 最好只单独和 if 使用,也就是双分支 if ... else ...。

任务1:请有感情的完成上述程序,好好体会 else if 。

→ if ... else if ... else if ... 多分支语句,理解很容易,但更多的是练习。练习中的体悟很重要。加油 ~

分支嵌套语句

如题,就是if 语句里,套另一个 if 语句。形式如下:
尽量别嵌套,实在要嵌套,别超过三层。

if(statement1) {
   
   
    if(statement2) {
   
   
        if(statement3)
            /* coude here */
    }
}

实际使用较少,大家知道这回事就行,练习时,用到再说,纯粹学,无意义,徒增烦恼和不会。

switch 语句

switch语句,几乎仅有两个场景会用到,一是:多分支 if ... else if ... else if ... ,其条件表达式是和某些具体数值判等时,使用 switch ,代码稍加易读;二是:炫技-展现奇技淫巧的时候,比如 case贯穿问题,比如明明是范围判断的问题,非要整理成,单个数值判断的问题,就是为了搞你。

但还是需要了解的,来看 switch 代码模板 ,除了 /* code here */,其余部分,固定格式。

switch(变量名) {
	case 变量可能的值1:
		/* code here */
		break;	// 处理完成,结束 switch
	case 变量可能的值2:
		/* code here */
		break;	// 处理完成,结束 switch
	case 变量可能的值3:
		/* code here */
		break;	// 处理完成,结束 switch
	default:	// 当变量值,不在上述的 case 中
		/* code here */
		break;	// 处理完成,结束 switch
}

再来看一个案例:按照成绩级别,输出对应分数区间:

  • 若输入 A,输出 [90, 100]
  • 若输入 B,输出 [80, 89]
  • 若输入 C,输出 [60, 79]
  • 若输入 D,输出 [0, 60]

点我,在线编程试一下👇

// 多分支 if...else if...else if... 版
#include <iostream>
using
C++程序基础(7):if与else语句 阅读详情

相关推荐

c++ (if,else)

还可以使用if语句根据用户输入采取行动,例如根据用户输入,我们可以检查两个数字,哪个大,哪个小,我们将在我们的文章中看到这个例子。有时候,当if语句中的条件为false时,最好执行一些代码,而不是语句变为true时执行的代码,用else我们可以计算如果条件为false时我们应该怎么做。好了,在上面的代码中,我们首先创建了一个布尔变量,默认情况下该值为true,然后我们检查如果条件为true,则在块中执行代码,如果条件为false,则在执行另一个代码中的代码。这是另一个例子,在这个例子中我们要检查两个数。

一个不懂编程的编程大佬,当一个人面对疾风,走上前去当一个逆行者,才是卫国黑客(AI终将代替人类) 607

【C++ 程序设计入门基础】- 第2节-分支结构

主要讲解C++中的分支判断

跟着飞哥学编程(全栈联盟) 2464

mcgs数据查表功能,用于大量数据对比查找对应数据,减少PLC代码

mcgs脚本实现数据查表功能

qq_24866535的博客 3271

MQTT(轻量级消息中间件)基本使用指南

MQTT(Message Queuing Telemetry Transport,消息队列遥测传输)是一种轻量级的发布 / 订阅模式(Pub/Sub)消息传输协议,专为低带宽、不稳定网络环境设计,广泛应用于物联网(IoT)、移动设备、传感器网络等场景(如空气净化器、智能家居设备的远程控制)。Eclipse Mosquitto 是一款轻量级、开源的 MQTT 消息服务器(Broker),由 Eclipse 基金会维护,专为低资源消耗和易用性设计。

墨鸦的博客 1万+

[官方培训]22-UE资产优化 Epic 肖月 笔记

Nanite+Lumen目标:面向TA,美术,不影响视觉的前提下,优化运行和编辑效率引擎:UE5.1延迟管线平台:主流PC,Windows 10 with DX12。

Tcohneyn的博客 1576

FPGA,关于安装使用libero IDE V9.2 及其gold floating license配置

3、license安装根据,下面的提示进行,跟随setting up the license server on a host教程操作。1、从官网下载Libero IDE v9.2(如下图中的Libero IDE v9.2 software)4、下载完成license解压包后还需要下载 Daemons license ,地址如下。(2)第一行并不是在内填写,而是直接用您电脑名替换掉(1)修改license.bat前四行是,其务必保持和案例位置相同(避免出错)............

JasonK的博客 4298

LFM调制信号分类与检测识别

支持识别LFM信号、间歇采样干扰(ISRJ)、灵巧噪声干扰(SNJ)、扫频干扰(SJ)、瞄准干扰(AJ)、阻塞干扰(BJ)、密集假目标干扰(DFJ)、密集假目标加灵巧噪声干扰(DFWSNJ)、距离欺骗干扰(DDJ)、距离欺骗加灵巧噪声干扰(DDWSNJ)。Faster-RCNN支持检测识别LFM信号、间歇采样干扰(ISRJ)、灵巧噪声干扰(SNJ)、扫频干扰(SJ)、瞄准干扰(AJ)、密集假目标干扰(DFJ)、密集假目标加灵巧噪声干扰(DFWSNJ)、距离欺骗加灵巧噪声干扰(DDWSNJ)等8种信号。

菜yuan~的博客 1029

【光斑定位】空间激光通信、光斑定位、CCD、光斑定位——13000字

0.完整源码获得方式 订阅MATLAB/FPGA教程,免费获得教程案例以及任意2份完整源码 ----------------------------------------------------------------- 空间激光通信是指以光波作为载波进行数据传输的一种通信方式。目前,空间激光通信己成为人们关注的焦点。在空间激光通信系统中,光斑定位是是一项关键技术。 本论文首先对国内外空间激光通信系统的研究现状进行了阐述,论述了空间激光通信的理论只是,并对CCD成像原理,...

FPGA/MATLAB学习教程/源码/项目合作开发 1291

Vue3 - Element Plus上传组件el-upload上传多个文件时,让on-change监听事件仅执行一次并获取最终文件列表方法(开启多选文件并手动上传,拿到文件列表统一循环调用接口上传)

vue3,elementplus,Upload上传,el-upload,文件上传组件,上传组件on-change里执行多次,取消自动上传后change重复执行问题,upload上传多个文件后导致on-change执行多次拿不到最终文件列表,Element-plus的upload组件on-change不断执行怎么办,上传多个文件多次执行调用,上传多个文件时如何只执行一次on-change方法拿到最终的文件列表,vue3elementplus上传组件开启多个上传后导致change方法执行好几次,仅调用一

🏆 前端领域优质创作者 1万+

基于FPGA的BP神经网络Verilog设计与Matlab仿真

BP(Backpropagation)神经网络是一种常见且广泛应用的神经网络类型,通过反向传播算法实现训练和学习。本文将介绍如何使用Verilog语言在FPGA上设计一个简易的BP神经网络,并使用Matlab进行仿真验证。BP神经网络由输入层、隐藏层和输出层组成。在上述Verilog代码中,我们定义了BP神经网络的输入层、隐藏层和输出层的神经元数量,并声明了相应的信号和参数。在上述Verilog代码中,我们定义了BP神经网络的输入层、隐藏层和输出层的神经元数量,并声明了相应的信号和参数。

2301_79326254的博客 560

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 【C++基础语法】03 C++ 程序逻辑结构、分支 if 及关系表达式
下一篇: 【LeetCode】题解- 866. 回文素数
老坛算粉
博客等级 码龄12年 708粉丝 73原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老坛算粉

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值