【问题标题】:What is the problem with this code to find the count of the digits of the same number that are divisible by the number?这段代码有什么问题要找到可以被数字整除的同一数字的位数?
【发布时间】:2020-04-02 06:22:43
【问题描述】:

我的代码给出了运行时错误:

int findDigits(int n) {
    int count = 0, num = n, rem;

    while (num != 0) {
        rem = num % 10;

        if (n % rem == 0) {
            count++;
        }

        num = num / 10;
    }
    return count;
}

可能是什么原因?

【问题讨论】:

  • 欢迎来到 SO。你得到的运行时错误是什么?请提供完整且可编译的代码sn-ps。
  • 对我来说,您要达到的目标并不完全清楚。请提供样本输入和预期输出。以及你得到的不正确的输出,如果有的话。
  • 提示:rem 的可能值范围是多少?对于该范围的限制,n%rem 的结果是什么?
  • 运行时错误是浮点异常吗?
  • 原因是 rem 可以为零导致被零除。

标签: c runtime-error logic


【解决方案1】:

问题是您将尝试计算某个数字的 0 模数。

假设您输入的是 10,那么第一次迭代时 num 将是 10,rem = 0 因为 10 % 10 == 0。然后在 if 语句的条件中,您将尝试计算 n % rem,即 10 % 0,这会导致错误。

你应该简单地在 if 语句中捕捉这种情况

if (rem != 0 && n % rem == 0)
{
    ...
}

这是有效的,因为如果你有一个像 if (A && B) {...} 这样的 if 语句,那么 B 的表达式只有在 A 的表达式导致 true(c 中的 1)时才会被执行。这是因为如果A 导致false,则表达式A && B 不可能是true

【讨论】:

    【解决方案2】:

    你的问题在这里:

    rem=num%10;
    
    if(n%rem==0)
    

    其余的可能结果在0..9的范围内。

    如果将0 放入条件表达式中,则会出现除以零错误。

    你必须先检查rem!=0,然后才能进行计算。

    【讨论】:

      【解决方案3】:

      除了数字为 0 时,您的逻辑没有任何问题。

      从号码中提取一个数字后,rem = num % 10;

      您应该先检查它是否为 0,然后再检查该数字是否可以被该数字整除。因为除以零是未定义的,并且是错误的根源。所以,如果rem == 0,不要增加count

      例如,考虑 n = 30:

      在第一次迭代中:rem = 30 % 10 = 0 => n % rem => ERROR (attempted 30 / 0)

      鉴于数字为 0,这可能发生在任何迭代中。

      解决方案:

      改变

      if (n % rem == 0) {
          count++;
      }
      

      到:

      // making sure that rem is not zero before dividing n by rem
      if (rem != 0 && n % rem == 0) {
          count++;
      }
      

      另外:最好将rem 命名为digit

      【讨论】:

        【解决方案4】:

        这段代码没有任何错误

        #include<stdio.h>
        int findDigits(int n) {
        
        int count=0,num=n,rem;
        
        while(num!=0)
        {
        
            rem=num%10;
            if(rem!=0){
            if(n%rem==0)
            {
        
                count++;
        
            }
            }
            num=num/10;
        }
        return count;
        }
        int main()
        {
            printf("%d",findDigits(405)); //enter the numbe to find digits that are divisible
            return 0;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-06
          • 2012-05-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多