gpt4 book ai didi

java - 完全数法

转载 作者:行者123 更新时间:2023-12-01 17:24:45 24 4
gpt4 key购买 nike

该程序应该接受用户输入并确定它是否是完美数。当我尝试编译它时,出现错误 Method testPerfect in class scalvert_Perfect can not be apply to given types;

  • testPerfect(num);
  • 必需:int,int
  • 发现:整数
  • 原因:实际参数列表和形式参数列表的长度不同

我的代码:

import java.util.Scanner;

public class scalvert_Perfect
{
public static void main ( String args[] )
{
Scanner input = new Scanner(System.in);
int test;
int num = 0;
int counter = 0;

do
{
System.out.print("How many numbers would you like to test? ");
test = input.nextInt();

}while(test < 1);

do
{
System.out.print("Please enter a possible perfect number: ");
num = input.nextInt();

testPerfect(num);
printFactors(num);

counter++;

}while(counter < test);
}


public static boolean testPerfect(int num, int test)
{
int sum = 0;

for(int i = 0; i < test ; i++)
{
if(num % i == 0)
{
sum += i;
}

}
if(sum == num)
{
return true;
}
else
{
return false;
}
}

public static void printFactors(int num)
{
int x;
int sum = 0;

for(int factor = num - 1 ; factor > 0; factor--)
{
x = num % factor;

if (x == 0)
{
sum = sum+factor;
}
}
if(sum != num)
{
System.out.printf("%d:NOT PERFECT",num);
}

if(sum == num)
{
System.out.printf("%d: ",num);

for(int factor=1; factor < num; factor++)
{
x = num % factor;
if(x == 0)
{
System.out.printf("%d ",factor);
}
}
}
System.out.print("\n");
sum = 0;
}


}

最佳答案

您的函数需要两个整数,因为:

public static boolean testPerfect(int num, int test)

你在这里用 1 个整数来调用它:

 testPerfect(num);

顺便说一句,这正是错误所说的:

功能:

testPerfect(num);

需要两个整数

required :int, int

但是你用一个来调用它:

found: int

所以错误是因为参数数量不正确:

reason: actual and formal argument list differ in length

关于java - 完全数法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15897930/

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