So, I understand how to perform calculations on integers represented in strings, and then print the result in a string. But I am lost in how to do the same with the decimal digit in the quantity represented in the string.
Here's how I did it with integers. This piece of code combines two integers:
int answer = 0; char str1[100]; int count = 0; int total = 0; int k = 0; int diff = 0; if (ele == ele2) { for (k = strlen(op1) - 1; k > -1; k--) { if ((strspn(operand, "+") == strlen(operand))) { answer = (op1[k] - '0') + (op2[k] - '0'); } else if ((strspn(operand, "-") == strlen(operand))) { answer = (op1[k] - '0') - (op2[k] - '0'); } total += (pow(10, count) * answer); count++; } sprintf(str1, "%d", total); printf("Answer: %s ", str1); }
Output
Example
12.2 + 14.5 // Three strings Answer: 16.7 // Answer as string
Current attempt:
for (k = strlen(argv[1]) - 1; k > -1; k--) { if (argv[1][k] == '.') { dec = k; } else { answer = (argv[1][k] - '0') + (argv[3][k] - '0'); total += (pow(10, count) * answer); count++; } } // needs to be converted to a long? // ele is the length of the operand total = total / pow(10, ele - dec); sprintf(str1, "%d", total); printf("Answer: %s ", str1);
source share