In my program, I need the user to enter coordinates, starting with a letter and finishing by a number. The format is "e6", for example. I want to write a function that converts the number into an int. With this example, i want the "6" to be converted to int 6. My problem comes from the fact that the number can go up to 11.
I tried this function:
int function(char c[]) {
if (c[2]=='0') {
return (int)c[1] * 10;
}
else if (c[2]=='1') {
return (int)c[1]*10 + 1;
}
else {
return (int)(c[1]-'0');
}
}
The problem is that it returns numbers unrelated to the input, like "490" if I enter "f10".
I hope my problem is clear enough so you can help me !
Answer: I understand now my error, and what -'0' means. The new working function is:
int function(char c[]) {
if (c[2]=='0') {
return (int)(c[1]-'0') * 10;
}
else if (c[2]=='1') {
return (int)(c[1]-'0')*10 + 1;
}
else {
return (int)(c[1]-'0');
}
}
Thanks to all of you !
Here you convert a digit character to its value by subtracting '0'
:
return (int)(c[1]-'0');
That's correct (although the cast is completely unnecessary).
But here you just use the digit character as though it were a value:
return (int)c[1] * 10;
Since '1'
is 49, the output is not surprising.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.