[英]How do I solve this middle number problem?
Write a program where the user inputs 3 float numbers and the program checks which is medium size number.编写一个程序,用户输入 3 个浮点数,程序检查哪个是中等大小的数字。 Example :
a = 1.5
, b = 7.8
, and c = 3.0
and output should be c
.示例:
a = 1.5
、 b = 7.8
和c = 3.0
,输出应为c
。 This is what I've tried and it worked for one case, but I'm still doing too much spaghetti code and I'm still learning how to write code efficiently.这是我尝试过的方法,它适用于一个案例,但我仍然在做太多的意大利面条式代码,而且我仍在学习如何有效地编写代码。 My code:
我的代码:
#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;
}
I'm still trying to get the hang of the if
loops and I was just confused with this problem.我仍在尝试掌握
if
循环的窍门,而我只是对这个问题感到困惑。 Do you have any suggestions?你有什么建议吗?
think of like, if a is medium , then b is medium, then c is medium.想想,如果 a 是中等,那么 b 是中等,那么 c 是中等。 Check if that hepls!
检查是否有帮助!
#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;
} }
If you can use C++:如果您可以使用 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.