I get a wrong answer here. and then when i reviewed my code, i realized the error.

what i did was to extract each digit one by one from each number. to extract the first digit, get the remainder by dividing the number by 10. the remainder is the first digit. to extract the second digit, divide the quotient from the first division by 10. the remainder is the second digit. to obtain the third digit, divide quotient from the second division by 10. the remainder is the third digit, etc., etc. until you reach the 9th digit.

sum the first digit from the first number with the first digit from the second number. if the sum is greater than 9, then there is a carry of 1 in the next operation. sum the second digit from the first number and the second digit from the second number and the carry from the first operation. if the sum of the second digits with the carry is greater than 9, then there is a carry in the next operation. sum the third digit from the first number and the third digit from the second number and the carry from the previous operation. if the sum is greater than 9, then there is a carry in the next operation. Repeat the cycle until you reach the 9th digits. During the process, count the number of carries.

The error i had was I forgot to reset the carry when the sum was less than or equal to 9. This led to a wrong answer which was made me upset and depressed. After a few minutes, i reviewed my code and realized the resetting error. Overconfidence kills.

#include "stdio.h"

int main() {

unsigned int x, y, i, rx, ry, num_carry, sum;

bool carry;

while (1) {

scanf("%d %d", &x, &y);

if (x == 0 && y == 0) {

break;

}

carry = 0;

num_carry = 0;

for (i = 0; i < 9; i += 1) {

rx = x % 10;

x = x / 10;

ry = y % 10;

y = y / 10;

sum = rx + ry + carry;

if (sum > 9) {

carry = 1;

num_carry += 1;

}

else {

carry = 0;

}

}

if (num_carry > 1) {

printf("%d carry operations.\n", num_carry);

}

else if (num_carry == 1) {

printf("1 carry operation.\n");

}

else {

printf("No carry operation.\n");

}

}

return 0;

}

## No comments:

## Post a Comment