gpt4 book ai didi

计算整数中数字出现的次数

转载 作者:行者123 更新时间:2023-11-30 14:23:19 26 4
gpt4 key购买 nike

我想计算某个数字在整数中出现的频率。我有以下代码:

int main()
{
printf ("Put numbers\n");

int cislo;
int s0,s1,s2,s3,s4,s5,s6,s7,s8,s9;

while(scanf("%d",&cislo)==1){
if (cislo<0)
printf ("Cislo %d, je zaporne, takove neberu", cislo);
continue;
}

s0=s1=s2=s3=s4=s5=s6=s7=s8=s9=0;
do{
(cislo/=10);
switch (cislo%10){
case 0: ++s0; break;
case 1: ++s1; break;
case 2: ++s2; break;
case 3: ++s3; break;
case 4: ++s4; break;
case 5: ++s5; break;
case 6: ++s6; break;
case 7: ++s7; break;
case 8: ++s8; break;
case 9: ++s9; break;
}
}while (cislo>0);

printf ("Zadane cislo se sklada z cislic: \n\n 0 ... %dx \n 1 ... %dx \n 2 ... %dx \n 3 ... %dx \n 4 ... %dx \n 5 ... %dx \n 6 ... %dx \n 7 ... %dx \n 8 ... %dx \n 9 ... %dx \n",s0,s1,s2,s3,s4,s5,s6,s7,s8,s9);

return 0;
}

它必须如何工作:

Put number:1111111111Number: 1111111111 include:0 ...  0x1 ... 10x2 ...  0x3 ...  0x4 ...  0x5 ...  0x6 ...  0x7 ...  0x8 ...  0x9 ...  0x

它实际上是如何工作的:

Put number: 1111111111Number: 1111111111 include:0 ...  1x1 ...  9x2 ...  0x3 ...  0x4 ...  0x5 ...  0x6 ...  0x7 ...  0x8 ...  0x9 ...  0x

有谁知道为什么吗?

最佳答案

mod后的数字相除:

 do{
switch (cislo%10){
case 0: ++s0; break;
case 1: ++s1; break;
case 2: ++s2; break;
case 3: ++s3; break;
case 4: ++s4; break;
case 5: ++s5; break;
case 6: ++s6; break;
case 7: ++s7; break;
case 8: ++s8; break;
case 9: ++s9; break;
}
cislo/=10;
}while (cislo>0);

因此,您在计数时漏掉了一位数字。

你的输入法不太好。因为,您只想接收一个整数:

while(scanf("%d",&cislo)!=1){

更合适。

您还可以使用数组 s[10] 代替 10 个整数。

关于计算整数中数字出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com