C# 为什么';%';在我的代码中,会产生另一个数字,而不是我自己计算时得到的数字?

C# 为什么';%';在我的代码中,会产生另一个数字,而不是我自己计算时得到的数字?,c#,modulo,C#,Modulo,我有我的代码,可以得到输入号码的位数。 但是如果我用手拨,我会得到另一个 让我们以125为例,将其调制10。让我们甚至把它放在一个while循环中,让我们的数字每轮除以10。 我们得到: 我们的总数是8,75。 但是如果我使用下面的代码,我们得到8 有人知道为什么会有这么大的不同吗 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用系统文本; 使用System.Threading.Tasks; 名称空间EvenOrOdd { 班级计划 {

我有我的代码,可以得到输入号码的位数。 但是如果我用手拨,我会得到另一个

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

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

有人知道为什么会有这么大的不同吗

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
名称空间EvenOrOdd
{
班级计划
{
静态void Main(字符串[]参数)
{
int num,sum=0,r;
Console.WriteLine(\n输入一个数字:);
num=int.Parse(Console.ReadLine());
while(num!=0)
{
r=num%10;
num=num/10;
sum=sum+r;
}
Console.WriteLine(“数字的位数总和:+总和”);
Console.ReadLine();
}
}
}

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

只需将
int
替换为
double
float
就可以了。

试试这段代码

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();
        }
    }
}
这里有两个问题

-

  • int num,sum=0,r;改为十进制数,和=0,r,这将考虑小数
  • 此逻辑似乎是另一个问题
    ,而(num!=0)
    ,以下是迭代结果
    • 迭代1-125模10=5
    • 迭代2-12.5 Mod 10=2.5
    • 迭代3-1.25 Mod 10=1.25
    • 迭代4-0.125 Mod 10=0.125

  • 并继续以0.125为准!=0这将继续

    您正在将数字解析为一个
    int
    ,这意味着数字将被舍入。
    12,5%10->2,5
    如何在
    int
    中存储2.5?您使用整数(int)存储结果。整数不能显示小数点,所以它只是将8.75保存为8。将整型改为浮点数,应该会得到小数点后的结果。@elgonzo我现在看到了。他输入一个整数,然后尝试对余数求和。然后前两条注释适用。
    数字的位数之和
    如果不理解上下文,我希望它是8(1+2+5)-特别是如果这是家庭作业。谢谢!你完全正确,我的逻辑在这里也很离谱,谢谢你指出这一点!:)
    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();
            }
        }
    }