2011-12-11 187 views
-1

這是一個非常基本的問題,我需要找到一個球體的面積和體積,但我收到此錯誤:錯誤C2065:未聲明的標識符

error C2065: 'v' : undeclared identifier 
error C2065: 'a' : undeclared identifier 

這裏是我的程序:

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

using namespace std; 
int r; 
int computeSphere(int r) { 
    double a,v; 
    a = 4*3.14* pow(r,2); 
    v = (4/3) * 3.14 * pow(r,3); 

    return a,v; 
} 

int main() { 
    cout << "Enter the radius: "; 
    cin >> r; 
    cout << fixed << setprecision(2); 

    computeSphere(r); 

    cout << "The area of a sphere of radius " << r << " is " << a << " and its "; 
    cout << "volume is "; 
    cout << v; 
    cout << endl; 

    return 0; 
} 

問題說該函數不應該執行任何I/O操作。 那麼我該如何顯示結果?

+2

這不是功能是如何工作的。檢查你在課堂上學到的內容,弄清楚你應該做什麼。 (你可以用指針,引用,結構體,類,宏或其他東西來做到這一點) – SLaks

+4

「返回a,v;」和「4/3」都不會做你認爲他們做的事。閱讀一本好書,並在再次介紹一些C++基礎知識時再試一次。 –

+0

可能重複[什麼是'未聲明的標識符'錯誤,以及如何解決它?](http://stackoverflow.com/questions/22197030/what-is-an-undeclared-identifier-error-and-how- do-i-fix-it) – sashoalm

回答

4

兩個問題:

  • 你不能從一個函數返回多個值。
  • 你沒有對你調用函數的返回值做任何事情。解決第一個問題

的一種方法是定義一個結構:

struct SphereStuff 
{ 
    double a; 
    double v; 
}; 


SphereStuff computeSphere(double r) 
{ 
    SphereStuff stuff; 
    stuff.a = ...; 
    stuff.v = ...; 
    return stuff; 
} 

int main() 
{ 
    SphereStuff s = computeSphere(42);  // *** 
    std::cout << s.a << ", " << s.v << "\n"; 
} 

還要注意如何我「收集」標有此函數的返回值(上線「***」 )。

-1
#include <iostream> 
#include <cmath> 
#include <iomanip> 

using namespace std; 
int r; 

double calc_a(int r){ 
    return 4*3.14* pow(r,2); 
} 

double calc_v(int r){ 
    return (4/3) * 3.14 * pow(r,3); 
} 

int main() 
{ 
    double a,v; 

    cout << "Enter the radius: "; 
    cin >> r; 

    a = calc_a(r); 
    v = calc_v(r); 

    cout << fixed << setprecision(2);  
    cout << "The area of a sphere of radius " << r << " is " << a << " and its "; 
    cout << "volume is "; 
    cout << v; 
    cout << endl; 

    return 0; 
} 
+4

音量功能不會做你認爲它的功能。 –

0

把它分成兩個功能

double Volume (int r) { return (4/3) * 3.14 * pow(r,3); } 
double Area (int r) { return 4*3.14* pow(r,2); } 

,然後用它像

double v = Volume(r); 
double a = Area(r); 
+0

問題是,問題說我只能使用1個功能 – user1092492

+0

我明白了。那麼我認爲奧利查爾斯沃斯給出的解決方案是好的。您還可以返回兩個雙打的數組(或指向數組的指針)。但是struct結構對我來說更加清晰;) – thim

+0

@ user1092492:請編輯您的問題以包含「僅限一個函數」要求。 – trashgod

相關問題