【问题标题】:Print every number with 0 in their digits (Only natural) [closed]打印每个数字中都有 0 的数字(只有自然)[关闭]
【发布时间】:2014-03-28 03:23:31
【问题描述】:

该程序要求用户插入一个数字。假设我们输入了 149。现在程序打印每个数字中包含 0 位的数字,直到数字 149(包括数字)。所以它将是 10,20,30,40,50,60,70,80,90,100,101...110..140 [假设限制是到 10000]

我一直在尝试这样做,但我只给每个人加了 +10,但不能做到 >100,它是 101,102..

【问题讨论】:

  • 听起来像是功课。那么,到目前为止,您自己尝试过什么?
  • 您是否尝试过将 int 转换为 char 数组然后检查该数组是否包含 '0'
  • 我会提示您另一种解决问题的方法:只需使用每个数字的校验和即可。
  • 考虑递归。模运算符可能会有所帮助。
  • 最简单的方法是设置一个从1maxfor 循环(例如,max 是你的149)并调用一个函数(你会写)命名为has_zero(n),它返回01(假或真)。考虑除法和余数来确定一个数字中是否有任何0 数字。在循环中使用%(模)和除(/)。

标签: c loops for-loop


【解决方案1】:

使用函数sprintf将整数转换为字符串,然后在字符串中搜索字符'0'。如果找到,则打印该号码。这是一个实现这个想法的简单工作程序。

#include <stdio.h>
#include <string.h>

#define MAXLEN 50    // max number of digits in the input number

int main(void) {
    char buf[MAXLEN + 1];   // +1 for the null byte appended by sprintf
    char ch = '0';          // char to be searched for in buf
    int i, x;
    if(scanf("%d", &x) != 1) {   
        printf("Error in reading input.\n");
        return -1;
    }
    for(i = 1; i <= x; i++) {   
        sprintf(buf, "%d", i); // write i to the string buffer and append '\0'
        if(strchr(buf, ch))  // strchr returns a pointer to ch if found else NULL
            printf("%d\n", i);
    }
    return 0;
}

您还可以提取给定范围内整数的每个数字并检查它是否为零。这是一个简单的实现。

#include <stdio.h>

int main(void) {
    int i, x;
    int r;
    if(scanf("%d", &x) != 1) {
        printf("Error in reading input.\n");
        return -1;
    }
    for(i = 1; i <= x; i++) {
        for(r = i; r > 0; r /= 10) {
            if(r%10 == 0) {
                printf("%d\n", i);
                break;
            }
        }
    }
    return 0;
}

【讨论】:

  • 是否可以只使用 if else 语句和 for 循环来做到这一点?
  • @user3130120 没有其他语句,没有,但没有转换为字符串,是的。
  • 对不起,我没有得到你。我只使用了一个for 循环和两个if 条件。你想怎么做?
  • 好吧,只使用 int, printf,scanf,if else,for。
  • @user3130120 是的,你可以做到。提取范围内整数的每一位,并与0进行比较。如果true,则打印该数字。
【解决方案2】:

简单的方法是遍历所有自然数直到目标数并测试它们中的每一个以查看它们是否有任何零位。请注意,非负整数i 的最后一位数字可以作为除以基数的余数(此处为i % 10)。还要记住,C 中的整数除法会截断小数,例如,(12 / 10) == 1

【讨论】:

  • 它可以是101,这意味着它是1
  • @user3130120 如果号码是101,那么您的顺序应该是:(101%10 == 0) -&gt; false(101/10) -&gt; 10(10%0 == 0) -&gt; true。其余的% 10 只检查最后一个数字,就像我说的那样。所以你需要一直除以10,直到你检查了所有的数字。 (当除法为零时,您可以停止,因为前导零不算在内。)
【解决方案3】:

首先,考虑将每个数字转换为char [],然后检查它是否包含'0'

继续阅读:

  1. How to check if a int var contains a specific number

  2. Count the number of Ks between 0 and N

【讨论】:

    【解决方案4】:

    我想这就是答案。

    int j;
    for(int i=1;i<150;i++){
       j=i;   
             while(j>0)
             {
             if(j%10==0)
             {
               printf("%d\n",i);
               break;
             }
             else 
               j=j/10;
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-13
      • 2021-09-22
      • 2013-03-20
      • 2021-05-22
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多