【问题标题】:Why iterate each digit in a number and find evenly divided digits not working?为什么迭代一个数字中的每个数字并发现均匀划分的数字不起作用?
【发布时间】:2016-08-15 01:46:13
【问题描述】:

我正在编写一个代码,其中输入一个输入来运行一些测试用例,在每个测试用例中,我们必须通过每个数字迭代数字,我们必须将它除以所采用的初始数字,如果它给出余数 0 那么我们需要增加计数,否则我们不需要增加计数,最后我们将打印计数。


数字12被分成两位数,1和2。当12被除 通过这些数字中的任何一个,计算的余数为 0;就这样 12中可整除的位数是2

编译器消息

浮点异常

代码如下,在c编译器中运行时,程序在接受输入后突然停止。

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int t; 
    int n[t],b,rem;
        int count =0;
    scanf("%d",&t);
    for(int a0 = 0; a0 < t; a0++){

        scanf("%d",&n[a0]);
    }
    for(int i=0;i<t;i++){
        b =n[i];
        while (n[i]) {
            rem = n[i] % 10;
            if(b%rem == 0)
                count++;

             n[i] = n[i] / 10;

         }
        printf("%d\n",count);
    }
    return 0;
}

.

【问题讨论】:

    标签: c arrays loops if-statement


    【解决方案1】:

    在您的代码中,在您编写int n[t] 时,t 未初始化。由于未初始化的自动局部变量的初始值是不确定的,并且使用它会调用undefined behavior,因此您的代码会显示 UB。

    你需要移动int n[t]的定义成功从用户扫描t的值。

    之后,从% 运算符的属性,引用C11,第 §6.5.6 章,(emphais mine

    / 运算符的结果是第一个操作数除以 第二; % 运算符的结果是余数。 在这两种操作中,如果 第二个操作数为零,行为未定义。

    所以,您需要确保在执行if(b%rem == 0) 时,rem 不是 0。您应该检查rem != 0 &amp;&amp; .... 以避免这种情况。

    也就是说,只是一个建议:VLA 不再是标准 C 的强制性部分(C11 以后),因此您可以使用指针并使用 malloc() 和系列分配动态内存。

    【讨论】:

    • @Jean-BaptisteYunès 更新了相关细节。
    • “VLA 不再是标准 C 的一部分”不正确。 可变长度数组在 C11 §6.7.6.2 和标准的一部分中有很好的定义。与 C99 不同的是不需要实现。见__STDC_NO_VLA__
    【解决方案2】:

    您可以在设置大小之前创建给定大小的数组。 另一个错误(逻辑错误)是您没有为每个数字重置计数器。 您最初的问题是您没有注意除以0。 这可能是一个解决方案:

    int main(){
      int t; 
      scanf("%d",&t);
      int n[t];
      for (int a0=0; a0<t; a0++){
        scanf("%d",&n[a0]);
      }
      for (int i=0; i<t; i++){
        int count = 0;
        int b=n[i];
        while (n[i]) {
          int rem = n[i] % 10;
          if (rem!=0 && b%rem==0)
            count++;
          n[i] = n[i] / 10;
        }
        printf("%d\n",count);
      }
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2014-12-29
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多