两个long long int的总和,当它们给出的结果大于long long int时?

时间:2015-04-10 16:04:32

标签: c math long-integer integer-overflow

当结果大于C中的long long int时,是否有可能对两个不同的long long int变量求和?

1 个答案:

答案 0 :(得分:0)

由于OP希望"在屏幕上打印结果",将数字分成2部分:最高有效数字和最低有效数字。

#include <stdlib.h>

void print_long_long_sum(long long a, long long b) {
  if ((a < 0) == (b < 0)) {  // a and b of the same sign?
    // Sum the Most-Significatn_Digits and Least-Significant Digit separately
    int sumLSD = (int) (a % 10 + b % 10);
    long long sumMSDs = a / 10 + b / 10 + sumLSD / 10;
    sumLSD %= 10;
    printf("sum = ");
    if (sumMSDs) {
      printf("%lld", sumMSDs);
      // Since sign already printed, insure next print is positive
      sumLSD = abs(sumLSD); 
    }
    printf("%d\n", sumLSD);
  } else { // No need to separate as there is no chance for overflow
    printf("sum = %lld\n", a + b);
  }
}