[英]C++ warning: control reaches end of non-void function
我需要修復程序的幫助。 它沒有運行。 我不斷收到警告控件到達非void功能的結尾。 我不知道如何解決。 請幫我。 該程序假定為查找球的體積或表面積。 我收到最后2條的警告}
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
char s = '\0';
const char SENTINEL = 's';
float radius, answer;
void get_radius (float&);
float surface_area (float);
float volume (float);
float cross_section (float);
const float PI = 3.14;
int main()
{
cout << "This program will let you input the radius of a sphere to find its volume or surface area." << endl << endl;
cout << "Enter 'v' for volume or 'a' for surface area of a sphere" << endl;
cout << "'s' to stop" << endl;
cin >> s;
while (s != SENTINEL)
{
get_radius (radius);
if(s == 'V')
{
volume (radius);
}
else if(s == 'A')
{
surface_area (radius);
}
cout << "Enter 'v' for volume or 'a' for surface area of a sphere" << endl;
cout << "'s' to stop" << endl;
cin >> s;
}
system("PAUSE");
return 0;
}
void get_radius (float& radius)
{
cout << "Please enter the radius of the sphere: " << endl;
cin >> radius;
}
float volume (float radius){
float answer;
answer = 4.0/3.0 * PI * pow (radius, 3);
cout << "The volume is: " << answer << endl;
}
float surface_area (float radius){
float answer;
answer = 4.0 * PI * pow(radius, 2);
cout << "The surface area is: " << answer << endl;
}
您的函數聲明必須與您要返回的內容匹配。 您必須確保要從聲明它們正在返回某些內容的函數返回值。
volume()和surface_area()正在使用cout打印內容,但未返回任何內容。
float volume (float radius){
float answer;
answer = 4.0/3.0 * PI * pow (radius, 3);
cout << "The volume is: " << answer << endl;
return answer;
}
float surface_area (float radius){
float answer;
answer = 4.0 * PI * pow(radius, 2);
cout << "The surface area is: " << answer << endl;
return answer;
}
聲明函數的類型時,需要返回該類型的值。 例如,您的函數:
float volume (float radius) {}
需要一個return語句返回float類型的值。
如果不需要該函數實際返回內容,則將其聲明為void,以使編譯器知道這一點。 在這種情況下:
void volume (float radius)
請小心,因為void函數一定不能返回值(不過,它們可以使用裸返回語句)。
還要注意,跳過return語句的潛在路徑可能會觸發此錯誤。 例如,我可以具有以下功能:
int veryBadFunction(int flag)
{
if (flag == 1) {
return 1;
}
}
在這種情況下,即使函數中有return語句,只要flag的值不是'1',它就會被跳過。 這就是錯誤消息寫成控制到達的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.