比较两个整数的商

Compare quotient of two integers

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

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

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

谢谢。

使用基础数学:

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

交换除数并乘以如下 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 中的任何操作溢出,则结果未定义。