2011-03-09 181 views
2
/* This program */ 

using namespace std; 

#include <iostream> 
#include <cmath> 
#include <iomanip> 
#include <fstream> 

void readit(); 
void calcit(int, int); 
void writeit(float, float, float); 
int distvels[4] = {15, 25, 35, 45}; 

int main() 
{ 
    readit(); 
    system("pause"); 
    return 0; 
} 

void readit() 
{ 
    int targetdist, angl; 

    cout << "Enter the distance (meters) to the target:" << endl; 
    cin >> targetdist; 
    cout << "Enter the angle to fire the cannon:" << endl; 
    cin >> angl; 
    cout << "\n---------------\n\n"; 
    calcit (targetdist, angl); 
} 

void calcit(int targetdist, int angl) 
{ 
    double distvals[4]; 
    double tyme[4]; 
    double maxhite[4]; 

    for (int i=0; i<4; i++) { 
     distvals[i] = (2 * sin(angl) * cos(angl) * (distvels[i] * distvels[i]))/9.8; 
     tyme[i] = (2 * cos(angl) * distvels[i])/9.8; 
     maxhite[i] = ((cos(angl) * cos(angl)) * (distvels[i] * distvels[i]))/9.8; 
    } 

    writeit(distvals, tyme, maxhite);  
} 

void writeit(float distvals[4], float tyme[4], float maxhite[4]) 
{ 
    cout << "Velocity  " << "time  " << "height  " << "distance " <<endl; 
    for (int i=0; i<4; i++) { 
     cout << distvals[i] << " " << tyme[i] << " " << maxhite[i] << " " << endl; 
} 

每當我運行程序時,我都會收到此錯誤代碼cannot convert double* to float for argument 1 to void writeit(float, float, float)。我嘗試了所有我能想到的方法來擺脫它,但沒有運氣。誰能幫忙?故障代碼爲

回答

3

你聲明的功能:

void writeit(float, float, float); 

但定義有它:

void writeit(float distvals[4], float tyme[4], float maxhite[4]) 
{ 
    // ... 
} 

修復聲明匹配:

void writeit(float[4], float[4], float[4]); 

這也是值得在此時此刻指出在這不做你認爲的事情。事實上,它是一樣的:

void writeit(float[], float[], float[]); 

這是與此相同:

void writeit(float*, float*, float*); 

那是因爲你不能按值傳遞數組,所以它退化爲指針,以取而代之的是數組的開始。

但是,您可以通過引用傳遞,並保持尺寸:

void writeit(float (&)[4], float (&)[4], float (&)[4]); // declaration 
void writeit(float (&distvals)[4], float (&tyme)[4], float (&maxhite)[4]) // definition 
{ 
    // ... 
} 

我甚至建議將它作爲參考給const,你將不會被改變它:

void writeit(float (&)[4], float (&)[4], float (&)[4]); 
void writeit(const float (&distvals)[4], const float (&tyme)[4], const float (&maxhite)[4]) 
{ 
    // ... 
} 

如果您使用std::vector<float>,這也會更容易,但這是另一個討論。

大量想想那裏;希望能幫助到你。


編輯只注意到另外一個問題,在你想的double數組傳遞給將要期待的float陣列的功能!挑一個並堅持下去。

+0

我固定的聲明喜歡你說它它的作品!謝謝你一直盯着這整天試圖找出它! – kalib

+0

@kalib:沒問題。我希望這篇文章有助於解釋將數組傳遞給函數的問題。 –

0

錯誤與您注意到的一樣 - writeit期待指向浮點數組的指針,並且您正嘗試將它傳遞給一個雙精度數組,這是一個不同的大小。最簡單的解決辦法是將writeit的參數聲明爲雙精度數組,以便它們匹配。除此之外,你需要在傳遞之前拷貝到浮點數組中(在拷貝時轉換每個元素)

0

函數原型與函數定義不同。因此,將其更改爲 -

void writeit(double*, double*, double*); 

和函數定義 -

void writeit(double distvals[], double tyme[], double maxhite[]) 
{ 
    // ...... 
} 

注意,數組的大小(即,可選的,其實編譯器將不考慮),因爲陣列衰減到指針。這就是爲什麼通常數組大小也作爲參數發送給函數的原因,並且是一種很好的做法。

+0

「功能簽名」。 「方法」在C++中沒有很好的定義。 :) –

+0

@Tomalak Geret'kal - 你是對的。通常術語*方法*用於成員函數:) – Mahesh

+0

在更廣泛的面向對象的世界中,當然,但在C++中它沒有很好的定義。 「成員職能」非常模糊。 :)最好避免。 –