【问题标题】:C++ warning: control reaches end of non-void functionC++ 警告:控制到达非 void 函数的结尾
【发布时间】:2015-05-16 04:00:11
【问题描述】:

我需要有关修复程序的帮助。它没有运行。我不断收到警告控制到达非 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() return 都没有。
  • 那我该如何解决。我试过 return 0;但它不起作用
  • 当你编写代码时,先从一些小而简单的东西开始,然后逐步构建。如果你这样做了,你就会确切地知道问题出在哪里,并且快速浏览一下教科书就会告诉你如何编写一个返回一些东西的函数。

标签: c++


【解决方案1】:

您的函数声明必须与您返回的内容相匹配。您必须确保从声明为返回某些内容的函数返回值。

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;
}

【讨论】:

  • 我能做些什么来解决它。我试过返回答案;但这无济于事
  • 你需要将它添加到你的浮动函数的末尾。
  • 我试过了。我不认为它需要返回任何东西。它只需要让我输入一个新的半径
  • 应该是另一个变量,但我的老师说不需要。我忘记摆脱了,我现在摆脱了它
  • 当我做返回答案时;对于两者,警告都消失了,但是当我输入半径时它没有给我答案。它只是重复按 v 或 a
【解决方案2】:

当你声明一个函数的类型时,你需要返回一个该类型的值。比如你的函数:

    float volume (float radius) {}

需要一个return语句返回一个float类型的值。

如果您不需要该函数实际返回某些内容,则将其声明为 void 以让编译器知道这一点。在这种情况下:

    void volume (float radius)

请小心,因为 void 函数不能返回值(不过它们可以使用简单的 return 语句)。

另请注意,跳过 return 语句的潜在路径可能会触发此错误。例如,我可以有这个功能:

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

在这种情况下,即使函数中有 return 语句,只要 flag 的值不是“1”,它就会被跳过。这就是为什么错误消息的措辞是控制到达...

【讨论】:

  • 我不需要它来返回任何变量,但我需要它循环并让我不停地重新开始,除非我按 s
猜你喜欢
  • 2012-10-24
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 2018-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多