如果…否则如果混淆c++

If...else if Confusion C++

本文关键字:如果 c++      更新时间:2023-10-16

我在使用if/else语句时感到非常困惑,我构造了一个程序来决定三个提供的整数中哪一个是最大值…我写了下面的代码:

int a,b,c,max;
cout<<"Please enter value 1: t";
cin>>a;
cout<<"Please enter value 2: t";
cin>>b;
cout<<"Please enter value 3: t";
cin>>c;
if(a>b)
    {
    if(a>c)
    max=a;
        }

else if(b>a)
    {
    if(b>c)
    max=b;
    }
else if(c>a)                 //here comes the problem
    {
    if(c>b)
    max=c;
    }
cout<<"The Max value among the given value is:t"<<max;

我为int a输入值12,为int b输入值13,为int c输入值14,(意思是如果我在第三个实例中提供最大值)它向我显示了一个垃圾值作为最大值(尽管有14),可能有什么问题请????我正在使用Dev c++ 5.5.1在32位windows 7.

更容易读的结构应该是这样的:

int maximum(int a, int b, int c) {
    int max = a; 
    if (b > max) { 
        max = b;
    }
    if (c > max) { 
        max = c;
    } 
    return max; 
}

或更短的

    if (a>= b&& a>= c)
            cout << "The largest number is:" << a<< endl;
    else if (b> =a&& b> =c)
            cout << "The largest number is:" << b<< endl;
    else if (c>= a&& c> =b)
            cout << "The largest number is:" << c<< endl;

正确格式化代码很简单,包括:

  • 正确对齐{}
  • 与缩进
  • 一致

int a,b,c,max;
cout<<"Please enter value 1: t";
cin>>a;
cout<<"Please enter value 2: t";
cin>>b;
cout<<"Please enter value 3: t";
cin>>c;
if(a>b) {
    if(a>c)
        max=a;
} else if(b>a) {
    if(b>c)
        max=b;
} else if(c>a) {
    if(c>b)
        max=c;
}
cout<<"The Max value among the given value is:t"<<max;
相关文章: