2017-08-09 203 views
-2

我正在编写一个程序,要求用户输入正整数并计算从1到该数字的总和。需要一些提示我做错了什么。用于循环以获取数字总和的Java

下面是代码:

public static void main(String[] args){ 
    Scanner keyboard = new Scanner(System.in); 
    System.out.println("Enter a positive integer"); 
    int getNumber=keyboard.nextInt(); 
    int x; 
    int total = 0; 
    for (x=1;x<=getNumber;x++) { 
     total=x+1; 
    } 
    System.out.println(total); 
} 
+3

做'总=总+ x'代替'总= X + 1',会做。 – GadaaDhaariGeek

+0

您可以调试并找出问题。 – Nipun

+0

什么是调试方法? – Mariusz

回答

0

逻辑应从

total=x+1; // you evaluate total each iteration to initialize it with x+1 

改为

total=total+x; // you keep adding to the existing value of total in each iteration 
0

得到的总和从1到要输入数字每次用新号码x增加total

so。

也有提示:

你想用你的循环申报int x。删除int x并执行以下操作:

for (int x=1; x<=getNumber; x++) { 
    total = total + x; 
} 
0

您的问题是:

后的总价值是错误的,因为这行:

total=x+1; 

它应该是:

total = total + x; 
0

更改为:

total=x+1; 

这样:

total=total+x; 
0

尝试以下代码:

public static void main(String[] args){ 
     Scanner keyboard = new Scanner(System.in); 
     System.out.println("Enter a positive integer"); 
     int getNumber = keyboard.nextInt(); 
     int x; 
     int total = 0; 
     for (x=1;x <= getNumber;x++) { 
      total += x; 
     } 
     System.out.println(total); 
    }