C中最多三个数字

Aak*_*pta 0 c

我有三个数字,m,n和p。我正在尝试使用嵌套的if..else if..else查找最大值。

这是我的相同代码:

#include <stdio.h>

int main() {
    // your code goes here
    float m,n,p;
    scanf("%f%f%f", &m,&n,&p);
    if(m>n){
        if(m>p){
            printf("%f",m);
        }
    }
    else if(n>p){
        if(n>m){
            printf("%f",n);
            }
        }
    else{   
        printf("%f",p);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我输入m = 4,n = 2,p = 11时。它什么都不打印!
最后的其他语句不应该起作用并将结果设为11吗?

R S*_*ahu 5

通过将查找最大值的逻辑移到某个函数来简化代码。

#include <stdio.h>

float max_of_two(float x, float y)
{
   return (x > y) ? x : y;
}

float max_of_three(float m, float n, float p)
{
   return max_of_two(max_of_two(m, n), p);
}

int main()
{
    float m,n,p;
    scanf("%f%f%f", &m,&n,&p);
    printf("%f", max_of_three(m, n, p));
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Wea*_*ane 5

迟到的答案。这个简单的解决方案不需要任何条件嵌套:

#include <stdio.h>

int main() {
    float m, n, p, max;
    if(scanf("%f%f%f", &m, &n, &p) != 3) {
        puts("Bad input");
        return 1;
    }
    max = m; 
    if(n > max) {
        max = n;
    }
    if(p > max) {
        max = p;
    }
    printf("%f", max);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)