[英]Java method keeps running before returning value
我试图让我的程序在运行完最后一个 for 循环后返回该值,但由于某种原因,它在 for 循环后多次循环返回。 我在返回之前添加了一个 System.print 来测试发生了什么,它循环了很多次。 第一个结果是我所期望的,但循环导致它不正确。 我怎样才能阻止这种情况发生?
import java.lang.Math;
import java.util.Scanner;
public class RussianExpo
{
static int counter = 0;
static int[] intArray = new int[25];
static int value = 1;
public static int expomod(int a, int b, int n)
{
while(true)
{
if (b == 0)
{
intArray[counter] = 1;
break;
}
if (b==1)
{
intArray[counter] = a;
break;
}
if (b>1)
{
if((b & 1) == 0);
{
intArray[counter] = 1;
a = (a*a);
b = (int) Math.floor(b/2);
counter++;
expomod(a,b,n);
}
if((b & 1) == 1);
{
intArray[counter] = a;
a = (a*a);
b = (int) Math.floor(b/2);
counter++;
expomod(a,b,n);
}
}
}
for (int i = 0; i < 25; i++)
{
if(intArray[i]>0)
{
value = value*intArray[i];
value = value % n;
}
}
System.out.println(value);
return value;
}
public static void main(String[] args)
{
Scanner SC = new Scanner(System.in);
System.out.println("Enter a");
int a = SC.nextInt();
System.out.println("Enter b");
int b = SC.nextInt();
System.out.println("Enter n");
int n = SC.nextInt();
System.out.println(expomod(a,b,n));
SC.close();
}
}
输出:
Enter a
30
Enter b
2
Enter n
35
25
30
15
15
如何在 for 循环中设置中断以退出循环? 在value = value % n;
之后设置中断value = value % n;
可能是错的,我不确定该程序的意图是什么,但我认为您的问题是递归调用
if((b & 1) == 1);
{
intArray[counter] = a;
a = (a*a);
b = (int) Math.floor(b/2);
counter++;
expomod(a,b,n); //This recalls the function!
}
如果第一个值是正确的,那么它似乎是函数运行完成后的答案,后续值来自返回,因为堆栈从递归调用中返回,删除了 expomod(a,b,n) 调用从 expomod() 函数内部可以解决这个问题。
简短的回答:
从 expomod() 内部删除对 expomod(a,b,n) 的任何调用,看看是否得到了想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.