繁体   English   中英

我如何解决这个中间数字问题?

[英]How do I solve this middle number problem?

编写一个程序,用户输入 3 个浮点数,程序检查哪个是中等大小的数字。 示例: a = 1.5b = 7.8c = 3.0 ,输出应为c 这是我尝试过的方法,它适用于一个案例,但我仍然在做太多的意大利面条式代码,而且我仍在学习如何有效地编写代码。 我的代码:

#include <stdio.h>

int main(){
    float a, b, c;

    scanf("%f %f %f", &a, &b, &c);

    if(a < b && c < a)
        printf("%.1f", a);
    else if(b < a && b > c)
        printf("%.1f", b);
    else if(c > a && c < b)
        printf("%.1f", c);
    else
    {
        printf("not good"); //I wrote this part to check if the code is good
    }




    return 0;
}

我仍在尝试掌握if循环的窍门,而我只是对这个问题感到困惑。 你有什么建议吗?

想想,如果 a 是中等,那么 b 是中等,那么 c 是中等。 检查是否有帮助!

#include <stdio.h>

int main(){

float a, b, c;

scanf("%f %f %f", &a, &b, &c);

if((a > b && a < c) || (a > c && a < b) ) 
    printf("%.1f", a);
else if((b > a && b < c) || (b > c && b < a))
    printf("%.1f", b);
else if((c > a && c < b) || (c > b && c < a))
    printf("%.1f", c);
else
{
    printf("not good"); //I wrote this part to check if the code is good
}




return 0;

}

如果您可以使用 C++:

#include <stdio.h>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
    float a, b, c;

    scanf("%f %f %f", &a, &b, &c);

    // Put them in a vector. Could use array, but vector more flexible
    vector<float> vals = {a,b,c};

    // Sort in numerical order
    sort (vals.begin(),vals.end());

    // Display the middle one
    printf("%.1f", vals[1]);

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM