简体   繁体   English

执行while循环(Java)

[英]Do while loops (Java)

Im trying to write a program to sum each digit of every 4 digit number. 我试图写一个程序来求和每个4位数字的每个数字。 For example, I start with 1000 and once 1001 is added the thousands become 2, hundreds become 0, tens becomes 0 and units becomes 1. This should keep adding each number until it reaches 9999. This is my code, it just outputs 9999. 例如,我从1000开始,一旦加了1001,千就变成2,百变成0,十变成0,单位变成1。这应该继续将每个数字相加,直到达到9999。这是我的代码,只输出9999。

int num = 1000, unit = 0, ten = 0, hundred = 0, thousand = 0, newNum = 0, sumth = 0, sumh = 0, sumten = 0, sumu = 0;

while (num <= 9999)
{
    unit = num%10;
    newNum = num/10;
    ten = newNum%10;
    newNum=newNum/10;
    hundred = newNum%10;
    thousand = newNum/10;
    num++;
}
sumth = thousand + sumth;
sumh = hundred + sumh;
sumten = ten + sumten;
sumu = unit + sumu;

System.out.println(sumth + " " + sumh + " " + sumten + " " + sumu);

Tidying this up a little for readability: 对此进行一些整理以提高可读性:

int num = 1000,
    sumThousands = 0,
    sumHundreds = 0,
    sumTens = 0,
    sumUnits = 0;

    while (num <= 9999)
    {
        int units = num % 10;
        int tens = (num / 10) % 10;
        int hundreds = (num / 100) % 10;
        int thousands = (num / 1000) % 10;

        sumUnits += units;
        sumTens += tens;
        sumHundreds += hundreds;
        sumThousands += thousands;

        num++;
    }

System.out.println(sumThousands + " " + sumHundreds + " " + sumTens + " " + sumUnits);

The output you'll get is: 您将获得的输出是:

45000 40500 40500 40500

This is expected. 这是预期的。 For the sequence of integers 1000..9999: 对于整数1000..9999:

  • In the thousands column, every digit 1..9 is repeated 1000 times 在千列中,每个数字1..9重复1000次
    • So the thousands sum is 1000(9+8+7+6+5+4+3+2+1) = 1000(9(10)/2) = 45000 因此千和为1000(9+8+7+6+5+4+3+2+1) = 1000(9(10)/2) = 45000
  • In every other column, every digit 0..9 is repeated 900 times 在每隔一列中,每个数字0..9重复900次
    • So the sums for the other columns are 900(9+8+7+6+5+4+3+2+1) = 900(9(10)/2) = 40500 因此其他列的总和为900(9+8+7+6+5+4+3+2+1) = 900(9(10)/2) = 40500

It should be shifted inside while loop 它应该在while loop内移动

while (num <= 9999)
    {
        unit = num%10;
        newNum = num/10;
        ten = newNum%10;
        newNum=newNum/10;
        hundred = newNum%10;
        thousand = newNum/10;

        sumth = thousand + sumth;
        sumh = hundred + sumh;
        sumten = ten + sumten;
        sumu = unit + sumu
        num++;    

    }


Output: 45000 40500 40500 40500 输出: 45000 40500 40500 40500
Working link: https://ideone.com/WrAX8D 工作链接: https : //ideone.com/WrAX8D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM