【问题标题】:Compare quotient of two integers比较两个整数的商
【发布时间】:2017-02-10 09:22:58
【问题描述】:

我正在使用定点代码(即只有 16 位和 32 位整数)。 现在我需要比较两个非常相似的整数的商,例如

int result = 705/239;
int result2 = 720/235;

我如何仅使用整数来判断哪个结果会更大?在这里使用浮点数当然更容易,但不可能。

谢谢。

【问题讨论】:

    标签: integer fixed-point


    【解决方案1】:

    交换除数并乘以如下compare 函数:

    #include <stdio.h>
    
    // -ve if dividend1 ÷ divisor1 is less than dividend2 ÷ divisor2
    // zero if dividend1 ÷ divisor1 is equal to dividend2 ÷ divisor2
    // +ve if dividend1 ÷ divisor1 is greater than dividend2 ÷ divisor2
    int compare(int dividend1, int divisor1, int dividend2, int divisor2) {
        int product1 = dividend1 * divisor2;
        int product2 = dividend2 * divisor1;
        return product1-product2;
    }
    
    void test(int dividend1, int divisor1, int dividend2, int divisor2) {
        int comparison = compare(dividend1, divisor1, dividend2, divisor2);
        char const* relation = (comparison < 0) ? "less than" : (comparison > 0) ? "greater than" : "equal to";
        printf("%d/%d is %s %d/%d.\n", dividend1, divisor1, relation, dividend2, divisor2);
    }
    
    int main() {
        test(705, 239, 720, 235);
    }
    

    注意事项:

    1. 如果比率相等,则两个商都不大。
    2. 这与比较dividend1/divisor1divident2/divisor2 不同,因为整数除法会截断商。例如,当除数大于被除数时,商始终为零。
    3. 如果compare 中的任何操作溢出,则结果未定义。

    【讨论】:

      【解决方案2】:

      使用基础数学:

      int d1=705;
      int d2=720;
      int s1=239;
      int s2=235;
      
      int result1=d1/s1;
      int result2=d2/s2;
      
      if (d1*s2>d2*s1)
          result1 is bigger
      else
         result2 is bigger
      

      【讨论】:

        猜你喜欢
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        • 2019-07-04
        • 2014-10-25
        • 2013-05-07
        • 2013-01-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多