简体   繁体   English

如何修复以下C程序的输出?

[英]How to fix the output of the following C program?

I have a problem with output of the following C program. 我对以下C程序的输出有问题。 It does not get me the correct output.I transform this program from the sum of two big numbers. 它没有为我提供正确的输出。我从两个大数之和转换了该程序。 So I get the output with some "errors" like "232423-3-4-34--3424" instead of "23242334343424". 所以我得到的输出带有一些“错误”,例如“ 232423-3-4-34--3424”,而不是“ 23242334343424”。 How do i fix this? 我该如何解决?

 #include<stdio.h>
int main() {
  int num1[255], num2[255], dif[255];
  char s1[255], s2[255];
  int l1, l2;

  printf("Enter Number1:\n");
  scanf("%s", &s1);
  printf("Enter Number2:\n");
  scanf("%s", &s2);

  for (l1 = 0; s1[l1] != '\0'; l1++)
    num1[l1] = s1[l1] - '0';

  for (l2 = 0; s2[l2] != '\0'; l2++)
    num2[l2] = s2[l2] - '0';

  int carry = 0;
  int k = 0;
  int i = l1 - 1;
  int j = l2 - 1;
  for (; i >= 0 && j >= 0; i--, j--, k++) {
    dif[k] = (num1[i] - num2[j] - carry) % 10;
    carry = (num1[i] - num2[j] - carry) / 10;
  }
  if (l1 > l2) {

    while (i >= 0) {
      dif[k++] = (num1[i] - carry) % 10;
      carry = (num1[i--] - carry) / 10;
    }

  } else if (l1 < l2) {
    while (j >= 0) {
      dif[k++] = (num2[j] - carry) % 10;
      carry = (num2[j--] - carry) / 10;
   }
  } else {
    if (carry > 0)
      dif[k++] = carry;
  }


  printf("Result:");
  for (k--; k >= 0; k--)
    printf("%d", dif[k]);

  return 0;
}

Your result includes negative numbers because the code doesn't correctly implement modulo-10 arithmetic. 您的结果包含负数,因为该代码未正确实现10模运算。 In lines like this: 在这样的行中:

dif[k] = (num1[i] - num2[j] - carry) % 10;

If subtraction num1[i] - num2[j] - carry is less than 0, you want to store the result of 10-subtraction. 如果减法num1[i] - num2[j] - carry小于0, num1[i] - num2[j] - carry存储10减法的结果。 There are languages where the % operator works like that in, but in C it returns a negative number, so -1 % 10 yields -1 and not 9. 在某些语言中, %运算符的工作方式与此类似,但是在C中,它返回负数,因此-1 % 10产生-1而不是9。

To fix the issue, the code needs to be more explicit, eg: 要解决此问题,代码需要更加明确,例如:

int sub = num1[i] - num2[j] - carry;
if (sub >= 0) {
    dif[k] = sub;
    carry = 0;
} else {
    dif[k] = 10 - sub;
    carry = 1;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM