我爲我的英語,而不是我的第一語言提前道歉。如何隨時保持一個隨機變量?
程序簡介:在算術序列中生成隨機第一項並生成隨機差分以得到下一項。然後要求用戶輸入第六個任期。
import java.util.Scanner;
public class Project{
static int diff;
public static int calcSeq(int num){
return num+diff;
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int diff = (int)(Math.random()*20)+1;
int term1 = (int)(Math.random()*10)+1;
int sum = term1;
int ans = 0;
System.out.println(term1);
for (int i = 1; i<=4; i=i+1){
int nextTerm = calcSeq(term1);
sum = sum + nextTerm;
System.out.println(sum);
}
int term6 = sum + diff;
System.out.println(term6);
System.out.print("Enter the sixth term of this arithmetic sequence: ");
ans = keyboard.nextInt();
if (ans == term6){
System.out.println("That is the correct answer.");
}
else if (ans != term6){
System.out.println("That is incorrect. Try again.");
}
}
}
對於前五項,差值保持相同並且是正確的算術序列。但是當到了第六學期時,差異會發生變化,並且序列不再正確。例如正確的序列可以是2,4,6,8,10,12。這裏的差別是2.但是當程序運行時,它就像2,4,6,8,10,15這是不正確的。所以我的問題是如何保持整個隨機差異不變? 謝謝
對不起,我很新的初學java和編程能解釋一下更簡單嗎? – kidGil
我想你想告訴我的是,第二個int diff與第一個int衝突,所以我應該刪除int以使它們相同?但我試過這樣做,仍然有相同的問題,第六學期使用不同的隨機差異 – kidGil
通常你會是對的,但是這是一個類項目,其中一個要求是包含至少一個自定義方法。所以不幸的是我不能使用你的代碼。任何其他想法? – kidGil