Skip to content

4.1 选择结构 if语句

发布时间:

作用:执行满足条件的语句
if语句的三种形式

  • 单行格式if语句
  • 多行格式f语句
  • 多条件的f语句
    1.单行格式if语句:if(条件){ 条件满足执行的语句}
    示例:
js
int main() {
    //选择结构-单行i语句
    //输入一个分数,如果分数大于69日分,视为考上一本大学,并在屏幕上打印
    int score =0;
    cout<<"请输入一个分数:" << endl;
    cin >> score;
    cout<< "您输入的分数为:" << score << endl:
    //if语句
    //注意事项,在i判断语句后面,不要加分号
    if (score > 600)
    {
    cout <<"我考上了一本大学!!!" << endl;
    }
    system("pause");
   return 0;
}
   

注意:i条件表达式后不要加分号

2.我行格式if语句:if (条件){ 条件满足执行的语句} else{ 条件不满足执行的语句}
示例:

js
int main() {
    int score = 0;
    cout<<"请输入考试分数:“ << endl;
    cin >> score;
    if (score > 600)
    {
    cout <<“我考上了一本大学”<<endl;
    }
    else
    {
    cout <<"我未考上一本大学”<<endl;
    }
    system("pause");
     return 0;
}
   
  1. 多条件的if语句:if(条件1){ 条件1满足执行的语句}else if(条件2){条件2满足执行的语句}…else{ 都不满足 执行的语句}
    示例:
js
int main() {
     int score = 0;
     cout << "请输入考试分数:” << endl;
     cin >> score;
     if (score > 600)
     {
     cout<< "我考上了一本大学”<<endl;
     }
     else if (score > 500)
     {
     cout<< “我考上了二本大学” <<endl;
     }
     else if (score > 400)
     {
     sout <<量我考上了三本大学”<<endi;
     }
     else
     {
     cout s< <“我未考上本科”<< endl;
     }
     system("pause");
     return 0;
}
   
js
 **嵌套if语句**:在if语句中,可以嵌套使用if号句,达到更精确的条件判断  
   

练习案例1:

•提示用户输入一个高考考试分数,根据分数做如下判断

•分数如果大于600分视为考上一本,大于500分考上二本,大于400考上三本,其余视为末考上本科;

•在一本分数中,如果大于700分,考入北大,大于650分,考入清华,大于600考入人大。

练习案例2:三只小猪称体
有三只小猪ABC,请分别输入三只小猪的体重,并旦判断哪只小猪最重

js
int main(){
int num1=20;
int num2=25;
    int num3=15;
if (num1 > num2)
{
     //A比B重
     if (numl >num3) // A比C重
     {
      cout《<“小猪A最重〞<< endl:
     }
    else //C比A重
    {    
    cout<<“小猪C最重〞<<endl;
    }
else
{
     //A比B重
     if (num2 >num3) // A比C重
     {
      cout《<“小猪B最重〞<< endl:
     }
    else //C比B重
    {    
    cout<<“小猪C最重〞<<endl;
    }
}
return 0;
}