#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int compare(char* num1, char* num2) {
int length1 = strlen(num1);
int length2 = strlen(num2);
if (length1 < length2) {
return 1;
}
else if (length1 > length2) {
return 0;
}
else {
for (int i = 0; i < length1; i++) {
if (num1[i] < num2[i]) {
return 1;
}
else if (num1[i] > num2[i]) {
return 0;
}
}
}
return 0;
}
void add(char* num1, char* num2, char* result) {
int length1 = strlen(num1);
int length2 = strlen(num2);
int i = length1 - 1;
int j = length2 - 1;
int k = 0;
int up = 0;
int sum;
while (i >= 0 || j >= 0 || up) {
int digit1, digit2;
if (i >= 0) {
digit1 = num1[i] - '0';
i--;
}
else {
digit1 = 0;
}
if (j >= 0) {
digit2 = num2[j] - '0';
j--;
}
else {
digit2 = 0;
}
sum = digit1 + digit2 + up;
up = sum / 10;
result[k++] = (sum % 10) + '0';
}
result[k] = '';
for (int i = 0, j = k - 1; i < j; i++, j--) {
char temp = result[i];
result[i] = result[j];
result[j] = temp;
}
}
void subtract(char* num1, char* num2, char* result) {
int length1 = strlen(num1);
int length2 = strlen(num2);
int borrow = 0, diff;
int i = length1 - 1;
int j = length2 - 1;
int k = 0;
while (i >= 0 || j >= 0) {
int digit1, digit2;
if (i >= 0) {
digit1 = num1[i] - '0';
i--;
}
else {
digit1 = 0;
}
if (j >= 0) {
digit2 = num2[j] - '0';
j--;
}
else {
digit2 = 0;
}
diff = digit1 - digit2 - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
}
else {
borrow = 0;
}
result[k++] = diff + '0';
}
while (k > 1 && result[k - 1] == '0') {
k--;
}
result[k] = '';
for (int i = 0, j = k - 1; i < j; i++, j--) {
char temp = result[i];
result[i] = result[j];
result[j] = temp;
}
}
void processLine(char* line) {
char num1[100], num2[100], optr, result[101];
sscanf(line, "%[^+-]%c%s", num1, &optr, num2);
if (optr == '+') {
add(num1, num2, result);
}
else if (optr == '-') {
int isNegative = 0;
if (compare(num1, num2)) {
isNegative = 1;
subtract(num2, num1, result);
}
else {
subtract(num1, num2, result);
}
if (isNegative) {
char tempResult[102];
tempResult[0] = '-';
strcpy(tempResult + 1, result);
strcpy(result, tempResult);
}
}
printf("%sn", result);
}
int main() {
FILE* file = fopen("input.txt", "r");
if (file == 0) {
printf("Error opening file.");
exit(1);
}
int n;
fscanf(file, "%d", &n);
fgetc(file);
char line[204];
for (int i = 0; i < n; i++) {
if (fgets(line, sizeof(line), file)) {
if (line[strlen(line) - 1] == 'n') {
line[strlen(line) - 1] = '';
}
processLine(line);
}
}
fclose(file);
return 0;
}
I wonder if the cords continue naturally.
I’m also curious if I wrote the name of the variable efficientl, andabout the role of differ and borrow in the subtract function.
Also, since it hasn’t been long since I started coding, I’d like you to let me know if there’s a way to modify it in the easiest way possible.
New contributor
고예빈 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.