c++ - Number changing value when assigned to variable? -
i have little problem when assigning result variable, happening first time me now. call convert() "aaa" parameter, here output:
aaa **676** *(value cout)* = 26^(3-1)*1 **675** *(value of variable)* +26 = 26^(3-2)*1 700 +1 = 26^(3-3)*1 701 701
and here code:
string alphabet="abcdefghijklmnopqrstuvwxyz"; unsigned long long convert(string &str){ unsigned long long wvalue=0; for(int i=0;i<str.size();++i){ size_t found=alphabet.find(str[i]); if(found==string::npos) cout<<"please enter lowercase letters of english alphabet!"<<endl; unsigned long long add=((found+1)*pow(26,(str.size()-(i+1)))); wvalue+=add; if(i>0)cout<<"+"; cout<<"\t"<<((found+1)*pow(26,(str.size()-(i+1))))<<" = "<<"26^("<<str.size()<<"-"<<(i+1) <<")*"<<(found+1)<<"\t"<<wvalue<<endl; } return wvalue; }
chances i'm missing awfully obvious, cannot figure out.
((found+1)*pow(26,(str.size()-(i+1))))
is doing calculation, , doing supposed to, result within cout-statment correct. variable substracted 1 in first 2 assignments.
pow
floating-point function. takes , returns floating point numbers. assigning floating-point number integer variable truncates integer number, might have been 675.9999999
before assignment, turn 675
when assigned integer variable add
.
cout
rounds floating-point numbers, depending on configuration example 6 significant digits. 676.0
better approximation 675.999
, see 676
in output.
since don't want calculate real numbers integral numbers, better stay integral functions. take 26 power of n
, better use multiplication n
times. since use loop, , have next power of 26 every character, best add variable in keep current power value, this:
unsigned long long currentfactor = 1; (...) { ... unsigned long long add = currentfactor * (found+1); wvalue += add; currentfactor *= 26; }
also note don't have find character in alphabet string. can use character arithmetic this:
int charnumber(char c) { if (c >= 'a' && c <= 'z') return c - 'a'; // calculate position of c relative 'a' else return -1; // error }
Comments
Post a Comment