2009-02-23 70 views
0

問候大家。編譯包含以下函數的腳本時遇到問題。發生三種錯誤,所有在同一行上,其中我設置距離+ =到距離[] []:將數組值保存到雙變量中

錯誤C2108:下標不是積分 類型錯誤C2108的:下標不是的積分 類型錯誤C2297:' + =':非法,右操作數的類型爲'double(*)[15]'

援助將大受歡迎。

double S_initial; 

double distances [15][15]; 
double order [15]; 
void Initialize() 
{ 
    double x, y ,z; 

    double distance = 0; 

    for (int i = 0; i <= 14; i++) 
    { 
     x = order [i]; 
     y = order [i + 1]; 

     distance += distances [x][y]; 
    } 

    S_initial = distance; 
} 
+0

當我是14時,y將是15,這是超出了距離的範圍... – Skilldrick 2009-02-23 12:10:36

回答

3

好了,數組下標xy不是一體型像int,但double類型:

double x, y, z; 
... 
distance += distances[x][y]; 

而且像數組沒有意義的1.46534th元素,所以編譯器抱怨。

1

停止使用double並使用int代替。

或者,如果您必須在順序數組中使用double,則需要決定如何將可能找到的任何非整數值四捨五入爲整數。 Math.Floor,Math.Ceiling等

2

x和y不是整數...您需要將整數作爲數組下標。

0

您不能使用浮點數來索引數組。使用int或甚至更好的size_t。

for (int i = 0; i <= 14; i++) 
{ 
    x = order [i]; 
    y = order [i + 1]; /* when i = 14, you invoke UB */ 

    distance += distances [x][y]; 
} 

在到第二部分:

double order [15]; 

是未初始化的,在使用時,因此調用UB。