在使用java中的递归来解决codeforce中的问题时,我遇到了问题。
package codeforces;
import java.util.Scanner;
public
class NewClass11 {
static int solve(int x, int y, int count)
{
if (x > y) {
return count;
}
else {
count++;
x = x * 3;
y = y * 2;
solve(x, y, count);
}
//here return statement required
}
public
static void main(String[] args)
{
Scanner ob = new Scanner(System.in);
int x = ob.nextInt();
int y = ob.nextInt();
int count = 0;
System.out.println(solve(x, y, count));
}
}
在这里,IDE希望我在resolve方法的最后一个括号中返回一个return语句。但是为什么这不能像c++代码那样工作?请建议我另一种方式。但是,如果我用c++编写代码,效果很好。
这是c++代码:
#include <iostream>
using namespace std;
int solve(int x, int y, int count)
{
if (x > y) {
return count;
}
else {
count++;
x = x * 3;
y = y * 2;
solve(x, y, count);
}
}
int main()
{
int x, y;
cin >> x >> y;
int count = 0;
cout << solve(x, y, count);
}
最佳答案
But why this is not work like as c++ code?
因为C++与Java不同。
在这种情况下适用的区别是C++不需要非void函数的所有分支都返回。所示的C++程序格式正确,因此可以编译。相反,如果函数执行到达最后一个花括号而没有return语句,则程序的行为是不确定的。
code with c++ that works well
它不能“很好地工作”。 C++程序的行为是不确定的。
任何值得使用的编译器都将警告这种情况。默认情况下,GCC,Clang和MSVC会警告显示的程序。
please suggest me another way.
没有“另一种方式”。根据IDE的建议,通过添加缺少的return语句来修复程序。
关于java - 递归(返回语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62998823/