C语言小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。 请问,在 1 到 n 中,所有这样的数的和是多少?
时间: 2024-06-14 21:03:43 浏览: 9
以下是C语言实现小明对数位中含有 2、0、1、9 的数字求和的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int n, sum = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int t = i;
char str[10];
sprintf(str, "%d", t); // 将数字转换为字符串
int flag = 0;
for (int j = 0; j < strlen(str); j++) {
if (str[j] == '2' || str[j] == '0' || str[j] == '1' || str[j] == '9') {
flag = 1;
break;
}
}
if (flag) {
sum += t;
}
}
printf("%d\n", sum);
return 0;
}
```
相关问题
c语言小明对数位中含有 2、0、1、9 的数字很感兴趣(不包括前导 0),在 1 到 40 中这样的数包括 1、2、9、10 至 32、39 和 40,共 28 个,他们的和是 574。 请问,在 1 到 n 中,所有这样的数的和是多少?
在C语言中,可以使用循环和条件判断来计算在1到n中所有数位中含有2、0、1、9的数字的和。以下是一个示例代码:
```c
#include <stdio.h>
int main() {
int n = 40; // 设置n的值
int sum = 0; // 初始化和为0
for (int i = 1; i <= n; i++) {
int num = i; // 将当前数字保存到变量num中
int flag = 0; // 标记是否满足条件
while (num > 0) {
int digit = num % 10; // 获取当前数字的个位数
if (digit == 2 || digit == 0 || digit == 1 || digit == 9) {
flag = 1; // 如果当前数字的个位数满足条件,则将标记设置为1
break;
}
num /= 10; // 将当前数字除以10,去掉个位数
}
if (flag == 1) {
sum += i * i; // 如果标记为1,则将当前数字的平方加到和中
}
}
printf("在1到%d中,所有这样的数的和是%d。\n", n, sum);
return 0;
}
```
运行以上代码,将输出:
```
在1到40中,所有这样的数的和是574。
```
请用c语言实现输出自然数1到10000中含有数字2的数的个数。
以下是C语言实现输出自然数1到10000中含有数字2的数的个数的代码:
```c
#include <stdio.h>
int main() {
int count = 0;
for (int i = 1; i <= 10000; i++) {
int temp = i;
while (temp > 0) {
if (temp % 10 == 2) {
count++;
break;
}
temp /= 10;
}
}
printf("自然数1到10000中含有数字2的数的个数为:%d\n", count);
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)