編寫一個要求整數的類num
確保它大於0
(數據驗證),並計算並返回以下總和系列號碼:while循環,似乎無法讓它得到正確的數據
1/num + 2/num-1 + 3/num-2 + …. (num-1)/2 + num/1
不要陷入整數除法!
通過調用num = 2;
來測試您的方法,您會預期結果爲2.5
。
public class LengthSeries
{
public static void main (String[] args)
{
//variable declarations
Scanner keyboard = new Scanner(System.in);
int num;
int sum = 0; // sum
int ctr = 1 ; //counter
//Accept the required data
System.out.print ("Enter a whole number greater than 0 : ");
num = keyboard.nextInt();
//Process the data in order to determine data
while (num <= 0){
System.out.println ("Sorry number invalid");
System.out.println ("please write a whole number greater than 0 : ");
num = keyboard.nextInt();
}
while (num <= 0){
sum += (ctr/num);
num -= ctr;
ctr++;
}
//Display the output
System.out.println();
System.out.println ("Your sum is: " +sum);
System.out.println ("\n\nWritten by: KinnahRose Lopez");
} //end main method
} //end LengthSeries class
'sum'是'int',它永遠不會是2.5。你需要使用'double'。 – Guy