Hey, I am having trouble powering numbers in assigned array and would appreciate it if someone could give me some guidance on why I am getting the wrong results.
Basically the user enters the number of digits they want to enter. I store that as a string so that I am able to test the length of the number with the digits.
string number;
cin >> number;
if (number.length() == digits) {execute the bottom}
after doing so, I then change the string into an integer, hoping I would be able to display each int by itself and it's square right next to it:
int i = 0, trials = 0;
while ( trials < digits ) {
stringstream ss(number);
s >> number;
int z = number[i];
cout << number[i] << " \t " << pow( z , 2 ) << endl;
i++;
trials++;
}
this is the result if number = 1234
1 2401
2 2500
3 2601
4 2704
I do not understand why the squares of those number are so off and weird. Really appreciate it if someone could give me advice on this problem. Thanks!
'number' is a string. Therefore number[i] is a single character in that string.
Say for example, 'number' contains the string "5". Then number[i] will be the character '5' which is really the integer 53 (53 == '5', because 53 is the ASCII code for the character '5').
Basically you have type problems. You're confusing strings/chars/integers and not converting between them properly.
EDIT:
Also you shouldn't be using pow() to square something. Just do z*z. Using pow for squaring is overkill and expensive.