c++警告:控制到达非空函数的结束

C++ warning: control reaches end of non-void function

本文关键字:函数 结束 警告 控制 c++      更新时间:2023-10-16

我需要帮助修复程序。它没有运行。我不断得到警告控制达到非无效函数的结束。我不知道怎么修理它。请帮帮我。这个程序的目的是求出一个球体的体积或表面积。我得到了最后2个}

的警告
#include <iostream>
#include <iomanip>
#include <cmath>
#include <math.h>
using namespace std;
char s = '';
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) {}

需要返回语句返回float类型的值

如果你不需要函数实际返回什么,那么声明它为void,让编译器知道。在本例中:

    void volume (float radius)

只是要小心,因为void函数一定不能返回值(尽管它们可以使用裸返回语句)。

还要注意,跳过return语句的潜在路径可能触发此错误。例如,我可以有这样一个函数:

    int veryBadFunction(int flag)
    {
        if (flag == 1) {
            return 1;
        }
    } 

在这种情况下,即使函数中有一个返回语句,只要flag的值不是"1",它就会被跳过。这就是为什么错误信息的措辞是control reaches…