C语言记算1到20 1出现的次数
时间: 2024-06-16 12:06:30 浏览: 17
要计算1到20中数字1出现的次数,可以使用循环结构和条件判断来实现。以下是一种可能的解决方案:
```c
#include <stdio.h>
int countOnes(int num) {
int count = 0;
while (num > 0) {
if (num % 10 == 1) {
count++;
}
num /= 10;
}
return count;
}
int main() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
sum += countOnes(i);
}
printf("数字1在1到20中出现的次数为:%d\n", sum);
return 0;
}
```
运行以上代码,输出结果为:数字1在1到20中出现的次数为:12
相关问题
题目描述 给定nn个整数的序列A1、A2、...、AnA1、A2、...、An,然后给出一个整数xx,求xx在序列中出现的次数。 输入描述 第一行为一个正整数nn(1≤n≤201≤n≤20); 第二行为用空格隔开的nn个整数(1≤Ai≤1001≤Ai≤100); 第三行为一个正整数xx(1≤x≤1001≤x≤100)。 输出描述 输出xx在序列中出现的次数。 用c语言
以下是用 C 语言实现的代码:
```c
#include <stdio.h>
int main() {
int n, x, count = 0;
scanf("%d", &n);
int a[n];
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &x);
for (int i = 0; i < n; i++) {
if (a[i] == x) {
count++;
}
}
printf("%d\n", count);
return 0;
}
```
首先读入整数序列和要查找的整数 x,然后使用 for 循环遍历整数序列,统计 x 出现的次数,最后输出结果即可。
运用c语言指针写一个、求一个字符串中最长的连续出现的字符,输出该字符及其出现次数,字符串中无空白字符(空格、回车和 tab),如果这样的字符不止一个,则输出第一个。 输入格式 第一行输入整数 N,表示测试数据的组数。 每组数据占一行,包含一个不含空白字符的字符串,字符串长度不超过 200。 输出格式 共一行,输出最长的连续出现的字符及其出现次数,中间用空格隔开。 输入样例: 2 Aaaaabbbbbcccccccdddddddddd Abcdefghigk 输出样例: d 10 a 1
请注意,以下代码可能存在 bug,仅供参考。
```
#include <stdio.h>
#include <string.h>
int main() {
int n;
scanf("%d", &n);
getchar(); // 读取换行符
while (n--) {
char str[201];
fgets(str, 201, stdin);
int len = strlen(str);
int maxCount = 0, count = 1;
char maxChar = str[0], curChar = str[0];
for (int i = 1; i < len; i++) {
if (str[i] == curChar) {
count++;
} else {
if (count > maxCount) {
maxCount = count;
maxChar = curChar;
}
count = 1;
curChar = str[i];
}
}
if (count > maxCount) {
maxCount = count;
maxChar = curChar;
}
printf("%c %d\n", maxChar, maxCount);
}
return 0;
}
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.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)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)