c - 为什么这个程序的输出是错误的?。数字的频率
问题描述
数字频率的程序
请帮助我使用此代码以获得清晰的输出。我是初学者,我使用数组制作了程序。我不知道它是否正确。用我自己的逻辑制作
int count(int a)
{
int c;
while(a>=1)
{
c++;
a=a/10;
}
return c;
}
int main()
{
//program to find frquency of the number
int a,n,d;
int b[100];
int e[100];
scanf("%d",&a);
n=count(a);
for(int i=n;a>0;i--)
{
b[i]=a%10;
a=a/10;
}
for(int i=1;i<=n;i++)
{
d=b[i];
e[d]++;//most probably this part error occurs
printf("%d\n",d); //used this this to confirm that i have correctly stored value in d.
}
for(int i=1;i<=n;i++)
{
printf("%d ",e[i]);
}
return 0;
}
解决方案
- 该行
int c;
应该是int c = 0;
- 该行
int e[100];
应该是int e[100] = {0};
以下code
可以工作:
#include <stdio.h>
int count(int a) {
int c = 0;
while (a >= 1) {
c++;
a = a / 10;
}
return c;
}
int main() {
// program to find frquency of the number
int a, n, d;
int b[100];
int e[100] = {0};
scanf("%d", &a);
n = count(a);
for (int i = n; a > 0; i--) {
b[i] = a % 10;
a = a / 10;
}
for (int i = 1; i <= n; i++) {
d = b[i];
e[d]++; // most probably this part error occurs
printf("%d\n", d); // used this this to confirm that i have correctly
// stored value in d.
}
for (int i = 1; i <= n; i++) {
printf("%d ", e[i]);
}
return 0;
}
此外,您可以使用snprintf
:
#include <stdio.h>
int main() {
int a;
int max = -1;
char buf[100];
int count[10] = {0};
scanf("%d", &a);
snprintf(buf, sizeof(buf), "%d", a);
for (int i = 0; buf[i] != '\0'; ++i) {
int temp = buf[i] - '0';
++count[temp];
if (temp > max)
max = temp;
}
for (int i = 0; i <= max; ++i)
printf("%d ", count[i]);
return 0;
}
推荐阅读
- bash - 将 csv 文件的 field(column) 中的每个值作为参数传递给 awk。Unix
- mongodb - 在 Atlas Search 中搜索两个数字字段
- r - R6 类函数未在 Shiny Module 服务器中提供输出
- android - 打开帐户设置活动 Android TV
- python - AWS Glue python shell 作业因内部服务错误而失败
- python - 渲染 Flask 模板两次显示 HTM 页面
- python - 运行“encode_images.py”(styleGAN)时出错
- python - 如何通过加快网格搜索和for循环的工作来优化脚本?
- android - UPNP/DLNA 服务器播放暂停在三星电视 android 上不起作用
- python - Seldon 核心中的 Flask 重定向替代方案