【发布时间】:2017-10-24 21:29:06
【问题描述】:
我正在尝试编写一个程序,它显示所有可能的两位数字并显示这些数字的总和。
例如:
10 - 1 + 0 = 1
11 - 1 + 1 = 2
12 - 1 + 2 = 3
..
98 - 9 + 8 = 17
99 - 9 + 9 = 18
我使用 while 循环来获取正数,如下所示:
public static void main(String[] args){
int count = 10;
while (count < 100) {
System.out.println("count:" + count);
count = count + 1;
}
System.out.print("Sum of Digits of " +sum);
}
我坚持要像示例中那样获取这些数字的总和。我没有运气在互联网上阅读了一些东西。
【问题讨论】:
-
您告诉了我们所需的输出,但没有告诉我们您得到的输出。你有错误吗?输出不正确?等
-
尝试将问题分解为更小的问题。在每个等式中,您都需要三个数字。您已经拥有的第一个(柜台)。现在想想如何根据计数器计算出另外两个数字。
-
获取单个数字应该不是问题,特别是因为您知道数字的最大大小(即最多 2 位):尝试
sum = count/10 + count %10; -
@jhhoff02 - 嗯,不。 While 循环工作正常,它显示了所有应有的正两位数。我似乎无法像示例中那样得到它们的总和。总和 = 计数 % 10;也许这样的事情会起作用?这就是我卡住的部分。
-
count%10可以得到个位,count/10可以得到十位。所以它应该是这样的: System.out.println("" + count + "的数字总和是 " + count/10 + " + " + count%10 + " = " + count/10+count%10 + ".");
标签: java while-loop sum digits