【问题标题】:Comparing Three Floats in a C Function比较 C 函数中的三个浮点数
【发布时间】:2017-08-19 02:26:35
【问题描述】:

我用 C 语言编写了这个,试图获得 get_extreme 的最大值,但它没有在编译器中返回结果。

它应该返回最大的浮点值,或者如果最大值是三个,则返回该结果。

int get_extreme(float num1, float num2, float num3) {

/* local variable declaration */
int result;

if (num1 == num2 && num2 == num3 ){
    result = num1;
}
else if (num1 > num2 && num2 > num3){
    result = num1;}
else if (num2 > num3 && num3 > num1){
    result = num2;}
else {
    result = num3;}

return result;
}

【问题讨论】:

  • 如果它应该返回一个浮点数,为什么结果定义为int?为什么函数返回int
  • 那么你尝试过的输入会返回什么?
  • 好的,所以我解决了这个问题,但现在它返回的结果很荒谬。
  • 那是因为你的算法完全错误。您只考虑了两种可能的排列。一共6个。

标签: c function if-statement max


【解决方案1】:

您已将结果定义为int。也是返回值。但是当你给结果变量赋值时,你赋值的是一个浮点数。

而且你的逻辑似乎是错误的。如果num1 大于num2 并且num3 大于num2 并且num1 大于num3,则返回num3。 将条件更改为:

if (num1>=num2&& num1>=num3) 
result=num1;
else if (num2>=num1&& num2>=num3) 
result=num2;
else
result=num3;

【讨论】:

  • 仍在抛出奇怪的数字……
  • hmm 你能写出产生错误结果的整个函数吗?
【解决方案2】:
float get_extreme(float num1, float num2, float num3) {

    /* local variable declaration */
    float result;

    if (num1 == num2 && num2 == num3) {
       result = num1;
    } else if (num1 > num2 && num1 > num3) {
       result = num1;
    } else if (num2 > num3 && num2 > num1) {
       result = num2;
    } else {
       result = num3;
    }

    return result;
 }

【讨论】:

  • 没有足够的排列。显然有 6 种可能的比较。
  • 这个功能肯定可以正常工作。你试过了吗?
  • 你有一个不必要的条件。第一个。如果最后一个都相等,则返回就好了。
猜你喜欢
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 2022-01-18
  • 2012-05-13
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
相关资源
最近更新 更多