[英]I'm trying to get my program to print, but nothing happens when I run it
這段代碼將兩個數字作為底數,然后將其與一個整數相乘,但是當我嘗試運行它時,它接受了數字,然后什么也沒有發生。
import java.util.Scanner;
public class RaisedToThePower
{
public static void main(String [] args)
{
Scanner reader = new Scanner(System.in);
int base;
int exponent;
double x;
System.out.println("Enter the base");
base = reader.nextInt();
System.out.println("Enter the exponent");
exponent = reader.nextInt();
x = base^exponent;
while (exponent > (-1));
{
System.out.println(x);
}
while (exponent <= -1);
{
System.out.println("Thanks for playing");
}
}
}
為什么什么都不打印:
您沒有打印任何東西,因為
while (exponent > (-1)) ;
的;
結束while語句,由於它是一個無限循環,因此您從不打印任何內容。
{
System.out.println(x);
}
這只是一個語句塊,不屬於while
要解決此問題:
while (exponent > (-1)) // no ; here
{
System.out.println(x);
}
如果指數大於-1,這仍將是一個無限循環。
下一陣子有同樣的問題。
附加問題:
x = base^exponent;
這不會執行冪運算。
^
是Java中的XOR運算符。 (請參閱Java運算符 )
要獲得指數的冪,您需要使用:
Math.pow(base, exponent);
從Java文檔:
返回提高到第二個參數的冪的第一個參數的值。
你有 ; 在每個while循環結束時while(指數>(-1)); 而且除了打印之外,您都沒有在兩個循環內執行任何操作。 任何循環被命中都會是無限循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.