C语言给定一个正整数(<100000),求该数数位上4的数量。 输入格式: 输入数据为数字,每行一个数字,处理到文件尾。 输出格式: 对于每行给定的数字,输出一行该数字数位上4的数量。 输入样例: 32 14 44 输出样例: 0 1 2
时间: 2024-05-16 07:16:19 浏览: 8
以下是C语言的代码实现:
```c
#include <stdio.h>
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
int cnt = 0;
while(n > 0)
{
if(n % 10 == 4) cnt++;
n /= 10;
}
printf("%d\n", cnt);
}
return 0;
}
```
对于每个输入的数字,我们可以通过不断除以10取余数的方法,逐位判断该位是否为4,如果是,则计数器加1。最后输出计数器的值即可。注意要循环读入多个数字,直到文件尾。
相关问题
c语言;给定一个三位正整数,输出其百位数字、十位数字及个位数字
答:将给定的三位正整数n(n>=100)分解为百位数a、十位数b、个位数c:
a=n/100;
b=(n-a*100)/10;
c=n-a*100-b*10;
输出百位数a、十位数b、个位数c:
printf("百位数:%d\n",a);
printf("十位数:%d\n",b);
printf("个位数:%d\n",c);
用C语言实现给定一个正整数,要求:1.求他是几位数,2.分别打印每一位数字,3。逆序打印每一位数字。
以下是用C语言实现给定一个正整数的要求:
```c
#include <stdio.h>
int main() {
int num, digits = 0;
printf("请输入一个正整数:");
scanf("%d", &num);
// 判断数字位数
int temp = num;
while (temp != 0) {
temp /= 10;
digits++;
}
printf("该数是%d位数\n", digits);
// 分别打印每一位数字
printf("每一位数字分别是:");
int divisor = 1;
for (int i = 1; i < digits; i++) {
divisor *= 10;
}
while (divisor != 0) {
int digit = num / divisor;
printf("%d ", digit);
num %= divisor;
divisor /= 10;
}
printf("\n");
// 逆序打印每一位数字
printf("逆序打印每一位数字:");
while (digits != 0) {
int digit = num % 10;
printf("%d ", digit);
num /= 10;
digits--;
}
printf("\n");
return 0;
}
```
您可以将上述代码保存为一个以`.c`为后缀的文件,然后编译运行即可。输入一个正整数,程序将会输出该数字的位数,分别打印每一位数字,并逆序打印每一位数字。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)