为什么我的代码中的“%”会产生另一个数字而不是我自己计算时得到的数字?

How come '%' in my code produces another number than the one I get when calculating myself?

我让代码获取输入号码的位数。 但如果我手动拨号,我会得到另一个 ...

让我们取 125 并 - 例如 - 用 10 调制它。我们甚至把它放在一个 while 循环中,让我们的数字每轮除以 10。 我们得到:

125%10 -> 5
12,5%10 -> 2,5
1,25%10 -> 1,25

我们的总和是 8,75。 但是如果我使用下面的代码,我们会得到 8.

有谁知道为什么会如此不同?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EvenOrOdd
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, sum = 0, r;
            Console.WriteLine("\nEnter a Number : ");
            num = int.Parse(Console.ReadLine());
            while (num != 0)
            {
                r = num % 10;
                num = num / 10;
                sum = sum + r;
            }
            Console.WriteLine("Sum of Digits of the Number : " + sum);
            Console.ReadLine();
        }
    }
}

您应该使用浮点类型,例如 float 或 double。 int 不能容纳数字“8.75”。

只需将 int 替换为 doublefloat 即可。

试试这个代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EvenOrOdd
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal num, sum = 0, r;
            Console.WriteLine("\nEnter a Number : ");
            num = int.Parse(Console.ReadLine());
            while (num >= 1)
            {
                r = num % 10;
                num = num / 10;
                sum = sum + r;
            }

            Console.WriteLine("Sum of Digits of the Number : " + sum);
            Console.ReadLine();
        }
    }
}

这里有 2 个问题

-

  1. int num, sum = 0, r; to be changed to decimal num, sum = 0, r;,这将使小数被考虑
  2. 这个逻辑好像又是一个问题while (num != 0),下面是迭代结果
    • Iteration1 - 125 Mod 10 = 5
    • Iteration2 - 12.5 Mod 10 = 2.5
    • Iteration3 - 1.25 Mod 10 = 1.25
    • Iteration4 - 0.125 Mod 10 = 0.125

继续,因为 0.125 是 != 0 这将继续