2010-01-27 49 views
0

我正在處理一個小問題,並花了好幾個小時試圖弄清楚我做錯了什麼。使用Dev ++編譯器,它有時會有一些神祕的錯誤信息。關於函數和錯誤檢查的新手C++問題

我試圖讓體積計算功能,並得到它的工作,但我有2個小尼特。我解決這個問題後,將工作在錯誤檢查。

  1. 隨着函數的增加,出於某種原因現在使用dev ++,程序不會暫停(按任意鍵繼續)。

  2. 卷是空白而不是數字。

感謝 PC

// The purpose of this program is to determine the Volume of a 
// square-based pyramid after the user inputs the Area and 
// the Height. 
#include <iostream> 
#include <iomanip> 
using namespace std; 
double calcvolume(double a, double h) 
{ 
    double volume; 
    volume = (a * h)/3; 
    return (volume); 

} 

int main() 
{         
    double area, height, volume;     // declare variables 

    cout << "Please enter the Area of the Square-based pyramid:";  // requests users input 
    cin >> area;              // assigns user input to area 

    cout << "Please enter the Height of the Square-based pyramid:";  // requests user input 
    cin >> height;  
                // assigns user input to height 
    cout << "Area= " << area << "\n";         // Prints user input for area 
    cout << "Height= " << height << "\n"; 
    calcvolume(area,height);  

    cout << "Volume= " << fixed << showpoint << setprecision(2) << volume << "\n"; // Prints resolution to the formula stored in volume 

    system("pause"); // forces DOS window to pause to allow user to utilize program 
    return 0; 
} 
+2

如果您在編寫函數進行計算時需要幫助,請發佈您已經提出的內容,我們將從此處爲您提供幫助。 – luke 2010-01-27 18:59:47

+1

我們希望看到你寫的內容無效 - 我們無法修復工作代碼。 – 2010-01-27 19:01:13

+1

如果你需要幫助來弄清楚爲什麼事情不起作用,那麼顯示什麼是有效的,而不是沒有用的。 – 2010-01-27 19:01:57

回答

1

你更新的代碼看起來是正確的,但你是不是存儲calcvolume返回值。您在calcvolume中聲明的音量變量與您在main中聲明的音量變量不同。這些變量中的每一個只能從它在聲明的函數內引用。

爲了節省體積,

calcvolume(area,height);

應該

volume = calcvolume(area,height);

這將在主函數中存儲從calcvolume返回的值在volume變量中。

+0

有趣。我認爲音量將通過該功能設置並返回。那麼我會.. 謝謝 PC – 2010-01-27 23:17:32

+0

你可以通過聲明'calcvolume'的參數爲引用來獲得這樣的行爲。我建議你花更多的時間來研究C++編程的教程和指南,但它是一種可以獨自使用的語言。 – Eric 2010-01-28 02:40:34

0

你要結果分配的calcvolume(area,height)主的volume如下:

volume = calcvolume(area,height); 

現在你可以放心地使用主音量變量。

我猜你的程序甚至沒有達到system("pause")行,並且崩潰了上面的行。這可能是因爲volume從來沒有設置任何東西,並持有垃圾數據。這個垃圾數據使cout << ...失敗。

之前您解決calcvolume(area,height)線,嘗試修復您的變量聲明,以使您的變量初始化爲零:

double area=0.0, height=0.0, volume=0.0; // declare variables 

現在再次運行它,看看它是否輸出Volume=0.00和暫停。

將變量初始化爲零或有意義的東西總是好的。否則,它們將被初始化爲隨機數據(無論這些數據是否已存在於這些內存字節中),並且會使故障排除變得更加困難。