gpt4 book ai didi

c++ - 程序在 C++ Tutor 中执行时有效,但在其他任何地方都无效

转载 作者:行者123 更新时间:2023-11-30 04:48:46 24 4
gpt4 key购买 nike

我正在按照欧几里德算法编写一个相当简单的程序(我们必须使用递归来编写它)。在 C++ Tutor 中执行时效果非常好但是当我在终端编译程序时,它已经给了我:

warning: control may reach end of non-void function [-Wreturn-type]

当我尝试在终端中执行它时,它会抛出:

runtime error: execution reached the end of a value-returning function without returning a value

(但我要返回一个值?)

为什么它可以在 c++ tutor 上运行,但在 Linux 终端上不能运行(使用 clang 编译器)?

我试图在函数中使用一堆额外的变量来使过程对我来说更清晰,但我仍然不明白为什么它认为会有我不会返回值的情况。

#include <iostream>

using namespace std;

int ggt(int a, int b){

int rest{0};
int zaehler{0};
int divisor{0};

if(a>=b){
zaehler=a;
divisor=b;

if(a%b==0){
return b;
}
else{
rest=a%b;
divisor=rest;
zaehler=b;

ggt(zaehler, divisor);
}
}
else{
zaehler=b;
divisor=a;

if(b%a==0){
return a;
}
else{
rest=b%a;
divisor=rest;
zaehler=a;

::durchlaeufe--;
ggt(zaehler, divisor);

}
}
}

int main(){

int a{40}, b{12};

cout << "Bitte Zaehler eingeben: ";
cin >> a;
cout << "\n";

cout << "Bitte Nenner eingeben: ";
cin >> b;
cout << "\n";

if(ggt(a, b)==0){
cout << "ERROR\n";
}
else {
cout << "Der groesste gemeinsame Teiler ist: " << ggt(a, b) << "\n";
}

return 0;
}

在这个例子中,a=40 和 b=12,结果应该是 4。这正是 C++ 导师所说的......

最佳答案

实际答案(递归调用时缺少返回值)已经给出。

我想添加一个更简单的版本供您比较并可能学到一些东西:)

int ggt(int a, int b)
{
if (a < b)
{
std::swap(a, b);
}

if (a%b == 0)
{
return b;
}

return ggt(b, a%b);
}

简要说明:

  • 当 a < b 确保 b 包含较小的值时的“交换”。
  • 在调用递归时直接计算“rest”(a%b)(这避免了存储中间值)
  • 如您所见,控制流更简单,因此更容易推断执行的每个步骤。

关于c++ - 程序在 C++ Tutor 中执行时有效,但在其他任何地方都无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55695883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com