【问题标题】:Count how many of a certain digit is present on a given number in C计算C中给定数字上存在多少特定数字
【发布时间】:2021-09-10 14:34:07
【问题描述】:

使用 while 循环,我需要计算第二个输入整数的数字中有多少第一个整数 (0-9) 并打印结果。

输入样本:2, 124218

输出样本:2

这是我下面的代码:

#include<stdio.h>
int main() {
    int a;
    int num; 
    int i;
    int rev = 0;
    int reminder;
    int count = 1;
    int ans;
    int last;

    scanf("%d",&a);
    scanf("%d", &num );

    while(num!=0)
    {
        reminder=num%10;
        rev=rev*10+reminder;
        num/=10;

        if(a==reminder){
            ans++; 

            last = ans%10;
    
            printf("%d", last);
        }
        count++; 
    }
    return 0;
}

【问题讨论】:

  • 你为什么要打印last
  • 您的程序似乎没有打印结果(ans 变量的最终值)。还不清楚计算rev 的目的是什么。是你的代码吗?你知道为什么它是这样写的吗?

标签: c


【解决方案1】:
#include<stdio.h>
#include<stdlib.h>
int main() {
int a, num, remainder, count = 0;

scanf("%d",&a);
scanf("%d",&num );
int temp = abs(num);
while(temp!=0)
{
    remainder=temp%10;
    temp/=10;
    if(a==remainder)
        count++; 
}
printf("%d",count);
return 0;
}

【讨论】:

  • 错误的主原型
  • 现在已经修复了。
  • 不是。 INT_MIN + main 的 UB 仍然错误
【解决方案2】:
int count_digit(const unsigned digit, int number)
{
    int count = 0;
    if(digit < 10)
    {
        while(number)
        {
            if(digit == abs(number % 10)) count++;
            number /= 10;
        }
    }
    else
    {
        count = -1;  //error 
    }
    return count;
}

int main(void)
{
    printf("%d\n", count_digit(5, 455675));
    printf("%d\n", count_digit(3, -35633435));
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多