char to int
Hello!
I am using a book to study from and I was wondering how exactly this line of code works:
result = (number[0] + number[1] + number[2] + number[3] + number[4] -4*'0'); |
specifically
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
using namespace std;
int main()
{
char
number[5], word[5], ch;
int
result, result2;
cout <<
"Enter a 4-digit number:";
cin >> number;
cout << int(char(2));
result = (number[0] + number[1] + number[2] + number[3] + number[4] -4*'0');
cout << "\Sum of digits =" << result;
cout <<
"\nEnter a 4-letter word:";
cin >> word;
ch = (word[0] + word[1] + word[2] + word[3]) / 4;
cout <<
"\nAverage char =" << ch << endl;
system(
"pause");
return
0;
}
|
There are several errors in that code.
This line:
|
result = (number[0] + number[1] + number[2] + number[3] + number[4] -4*'0');
|
should instead be:
|
result = (number[0] + number[1] + number[2] + number[3] - 4*'0');
|
The reason for the
- 4*'0'
is that the line is a simplification of this:
1 2 3 4
|
result = number[0] - '0'
+ number[1] - '0'
+ number[2] - '0'
+ number[3] - '0';
|
Also I think this line:
would make more sense and be more useful in the context, written like this:
At line 16,
"\Sum of digits ="
should be
"\nSum of digits ="
Topic archived. No new replies allowed.