gpt4 book ai didi

java - 如何以 (System.out.println(numbers)); 打印的方式将数字相加数字++;

转载 作者:行者123 更新时间:2023-12-01 13:05:19 25 4
gpt4 key购买 nike

我如何以与打印数字相同的方式将数字加在一起。

    System.out.println(numbers);
numbers++;

这会像这样打印。

    1
2
3
4

等等

如何将它们加在一起为 1+2+3+4

这是我当前关于这个问题的代码。这是我在赫尔辛基大学的 MOOC 中进行的练习,我住在美国,因此由于 8 小时的时差,很难寻求帮助。

    public static void main(String[] args) {
Scanner reader = new Scanner(System.in);

System.out.print("Until What?:");
// the user inputs a number here
int blockExe = 1;
// the blockExe variable is supposed to store a count of how many times the
// block has been executed which i belive should be limited to the user input
int userIn = Integer.parseInt(reader.nextLine());
int sum = userIn + blockExe;
// i am supposed to add the number of block executions the user input
// each time adding 1 to the execution so 1+2+3
// then printing the sum of those numbers

while (blockExe <= userIn) {
blockExe += 1;
if (blockExe + userIn == sum) {
break;
}
}
System.out.println("Sum is:" +sum);

}

}

最佳答案

此代码不明确:

while (blockExe <= userIn) {
blockExe += 1;
if (blockExe + userIn == sum) {
break;
}
}

也许你想要这个:

int sum=0;
for(blockExe = 1;blockExe <= userIn; blockExe ++) {
sum+=blockExe;
}

关于java - 如何以 (System.out.println(numbers)); 打印的方式将数字相加数字++;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23306164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com