添加int数?

问题描述 投票:-1回答:1
public static int addIntNumbers()
{
    int input = int.Parse(Console.ReadLine());
    int sum = 0;
    while (input !=0)
    {        
        sum += input % 10;
        input /= 10;
        Console.WriteLine(sum);
    }

    return sum;
}

我不明白这个语法。后面的 while 状况。sum += input % 10这基本上意味着 sum = sum(which is 0) + input % 10所以,假设我输入了24,那么这个总和应该是4,我想?

然后是第二行,我不知道它在做什么。

有什么建议吗?

c# int
1个回答
0
投票

最好的方法可能是添加注释。然而,我已经可以看出,不管是谁写的,都不知道自己在做什么。首先,没有注释,命名很糟糕,而且IO实际上是在函数内部进行的。

//The name is not right. This is not a proper sum function
//I think it is getting a sum of all digits in the input
public static int addIntNumbers()
{
    //Get a input from the user, parse it to int
    //That really belons outside. Just the int in per argument
    int input = int.Parse(Console.ReadLine());
    //Initialize sum to 0
    int sum = 0;

    //Input is also used as sort of "running variable".
    //The loop will break if input reaches 0
    while (input !=0)
    {
        //sum = sum + input % 10
        //It tries to divide input by 10, get's the rest, then adds that rest to sum
        sum += input % 10;
        //Divide input by 10. Note that all decimal parts will be dropped
        //That means it will reach 0 invariably
        input /= 10;
        //Output the current sum for debugging
        Console.WriteLine(sum);
    }
    //The function returns
    return sum;

}

0
投票

你的代码计算一个整数的逐个数字的总和(如果输入是正数,总和就是正数,如果输入是负数,总和就是负数).如果你是一个C#初学者,这可能会帮助你。

    while (input !=0)
    {

        sum = sum + (input % 10); //sum = sum + remainder of division by ten (separation of least significant digit)
        input = input / 10; //input is integer-divided by ten, which results in discarding of the least significant digit
        Console.WriteLine(sum);
    }

如果你不明白的话,请熟悉一下这两者之间的区别。 4/64.0/6.第一个是整数除法,另一个是浮点除法。


0
投票

一些事情可以帮助你理解这里发生的事情。

首先,假设你是在Visual Studio中, 你可以在你的代码中设置一个断点 通过点击左边的行号,在空白处。一个红点会显示出来,当你的代码到达该点时,它会暂停。当暂停时,你可以查看 "本地 "选项卡或将鼠标悬停在代码中的变量名上,以查看该时间点的值。然后,你可以使用F10一次前进一行,看看事情是如何变化的。

其次,=运算符类似于+=运算符,除了除法。所以,"x = 10 "与 "x = x 10 "完全一样。

这个程序是把你输入的数字的每一位数字相加,得到1位数,加起来求和,然后除以10,把旧的1位数去掉。

© www.soinside.com 2019 - 2024. All rights reserved.