I'm trying to make an addition ( ) with the numbers of a string. I have tried to do this:
void add_numbers(string z)
{
char result = 0;
for (int i = 0; i < strlen(z); i )
{
result = result z[i];
}
printf("%c", result);
}
int main(void)
{
string z = "2222";
add_numbers(z);
}
The output should be 10
, because 2 2 2 2 = 10. But, actually, the output is ]0;
What am I doing wrong?
CodePudding user response:
The variable "result" is not char. It must be int.
CodePudding user response:
#include <stdio.h>
typedef char* string;
void add_numbers(string z)
{
int result = 0;
while(*z)
{
result =*z -'0'; // I love the symbol sequence here: =*z -'0';
}
printf("%d", result);
}
int main(void)
{
string z = "2222"; // Correct answer is 8
add_numbers(z);
}
Output
Success #stdin #stdout 0.01s 5444KB
8
CodePudding user response:
Don't use char for 'result' (it is prone to UB as it will easily overflow), instead use something like int. You also cannot use the '%c' format specifier in printf, as it will print the character representation of its argument. You also have to remember the characters of a string are (not guaranteed, but most likely) stored in ASCII format, where the numerical characters do not correspond to their actual integer numbers. Subtract a '0' from each digit to accomodate for this.
result = result z[i];
should be
result = result z[i] - '0';
or even better
result = z[i] - '0';