2013-05-21 79 views
0

將結果賦給一個變量時,我遇到了一些小問題,這是我現在第一次發生。我叫()轉換爲「AAA」作爲參數,這裏是我的輸出:分配給變量的數值變化值?

aaa 

**676** *(value from cout)* = 26^(3-1)*1  **675** *(value of the variable)* 

+26 = 26^(3-2)*1 700 

+1 = 26^(3-3)*1 701 

701 

這裏代碼:

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 only lowercase letters of the 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; 
} 

機會是我失去了一些東西非常明顯的,但我不能想辦法。

((found+1)*pow(26,(str.size()-(i+1)))) 

正在做計算,並且它按照它應該做的,cout-statment中的結果是正確的。但是前兩個任務中的變量減1。

回答

2

pow是一個浮點函數。它需要並返回浮點數。將浮點數賦給整型變量會將其截斷爲整數,因此它可能在賦值之前爲675.9999999,如果賦值給整型變量add,該賦值將變爲675

cout也舍入浮點數,取決於配置,例如對6個有效數字。 676.0是比675.999更好的近似值,所以您在輸出中看到676

由於您不想用實數進行計算,只能用整數進行計算,所以最好使用積分函數。採取26的權力n,最好使用乘法n次。既然你已經使用一個循環,並希望有26個爲每個字符的下一個動力,最好是添加在其中保持當前的功率值的變量,就像這樣:

unsigned long long currentFactor = 1; 
for (...) { 
    ... 
    unsigned long long add = currentFactor * (found+1); 
    wvalue += add; 
    currentFactor *= 26; 
} 

還要注意,不必在字母串中找到字符。你也可以使用字符算術來做到這一點:

int charNumber(char c) { 
    if (c >= 'a' && c <= 'z') 
     return c - 'a'; // calculate the position of c relative to 'a' 
    else 
     return -1;  // error 
} 
+0

謝謝你的答案。我仍然不明白爲什麼26^2在從double轉換爲int時被截斷爲25,但至少我知道這是關於什麼,並可以採取相應的行動。 –

+0

我剛剛注意到你想讓最右邊的(最後一個)字符在你的總和中有最小的值。要通過「在每個步驟中乘法」技術實現這一點,您必須在字符串上反向迭代。我建議爲此使用迭代器。要反向迭代,只需使用'string.rbegin()'和'string.rend()'並在每一步中遞增迭代器。一個例子可以在這裏找到(http://www.cplusplus.com/reference/string/string/rend/)。 – leemes

+0

對於浮點舍入錯誤,[請閱讀此非常翔實的文章](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html#680)。我知道這很長,你不需要全部閱讀,但特別是關於舍入錯誤的部分解釋了代碼中發生了什麼。 – leemes