如何在C语言中使用if语句比较多个数据并找出最大值与最小值
如何在C语言中使用if语句比较多个数据并找出最大值与最小值
兄弟,我看你写到一半卡住了,其实用if语句找出多个变量里的最大值和最小值没那么复杂,咱们一步步来解决你的问题。
首先,你之前只比较了rice和oil,这显然不够,因为还有suger和salt没参与比较。更稳妥的方式是先把其中一个变量的值作为初始的最大/最小值,然后逐个和剩下的变量比较,只要遇到更大(或更小)的就更新对应的变量,这样就能覆盖所有情况了。
下面是修改完善后的完整代码,每一步都加了注释,你可以跟着理解:
#include<stdio.h> int main(){ // 定义四个商品价格变量 float rice, oil, suger, salt; // 存储最大和最小价格的变量 float highest_price, lowest_price; // 获取用户输入的各个商品价格 printf("Enter the price of rice :\n"); scanf("%f", &rice); printf("Enter the price of oil :\n"); scanf("%f", &oil); printf("Enter the price of suger :\n"); scanf("%f", &suger); printf("Enter the price of salt :\n"); scanf("%f", &salt); // 第一步:初始化最大和最小值为rice的价格 highest_price = rice; lowest_price = rice; // 第二步:和oil比较,更新最大/最小值 if(oil > highest_price){ highest_price = oil; } if(oil < lowest_price){ lowest_price = oil; } // 第三步:和suger比较,更新最大/最小值 if(suger > highest_price){ highest_price = suger; } if(suger < lowest_price){ lowest_price = suger; } // 第四步:和salt比较,更新最大/最小值 if(salt > highest_price){ highest_price = salt; } if(salt < lowest_price){ lowest_price = salt; } // 最后输出结果 printf("The highest price is: %.2f\n", highest_price); printf("The lowest price is: %.2f\n", lowest_price); return 0; }
当然,如果你觉得写这么多if有点繁琐,也可以用嵌套的if-else来简化比较逻辑,比如找最大值的时候可以这么写:
// 用嵌套if找最大值的方式 if(rice >= oil){ if(rice >= suger){ if(rice >= salt){ highest_price = rice; } else { highest_price = salt; } } else { if(suger >= salt){ highest_price = suger; } else { highest_price = salt; } } } else { if(oil >= suger){ if(oil >= salt){ highest_price = oil; } else { highest_price = salt; } } else { if(suger >= salt){ highest_price = suger; } else { highest_price = salt; } } }
不过这种嵌套写法虽然逻辑没问题,但变量多了之后会显得很乱,所以更推荐第一种“初始赋值+逐个比较”的方式,代码更清晰,也容易维护。
你可以把上面的代码复制运行试试,输入几个不同的价格,就能看到正确的最大和最小值啦!
备注:内容来源于stack exchange,提问作者jobayer hasan
相关产品推荐
相关产品推荐

