专业编程基础技术教程

网站首页 > 基础教程 正文

聊聊C++知识点中的 if else if语法及其应用

ccvgpt 2024-11-20 13:02:22 基础教程 7 ℃

大家好,欢迎继续关注,我是发哥,今天我们来聊聊if else if语法及其应用。实际生活中,我们会发生的情况不止两种,有可能有两种以上,比如考试成绩,就有优秀,良好,中等,一般和差五种。

因此C++中的if else if就是来解决上述所描述的类似情况。if else if语法格式如下:

聊聊C++知识点中的 if else if语法及其应用

if (条件表达式1)

{

语句块1;

}

else if (条件表达式2)

{

语句块2;

}

else if (条件表达式3)

{

语句块3;

}

以下举个上述所描述成绩例子,源代码如下:

#include <iostream>


using namespace std;



int main()

{

int score = 0;



while(1)

{


cout << "请输入分数(注意如果大于100,则退出程序):" << endl;

cin >> score;

if (score > 100)

{

cout << "退出程序" << endl;

break;

}

else if (score >= 90)

{

cout << "优秀" << endl;

}


else if (score >= 80)

{

cout << "良好" << endl;

}

else if (score >= 70)

{

cout << "中等" << endl;

}

else if (score >= 60)

{

cout << "一般" << endl;

}

Else

{

cout << "差" << endl;

}

}

return 0;

}

程序运行结果如下截图所示。


今天就讲到这儿,下节课讲switch语法及其应用。

最近发表
标签列表