找到其中正好有 2 个 9 的数字

Find the numbers with exactly 2 nines in them

本文关键字:数字      更新时间:2023-10-16

我们输入n个数字,程序必须输入正好有2个'9'的数字。(例如,如果我们输入 9193,那么程序将键入它,但如果我们编写 73999 或 256,它不会给出任何输出)。所以我写了这段代码

int main(){
int a, n, i, count=0, y;
cin>>n;
for(i=1; i<=n; i++){
    cin>>a; y=a;
    while(y>0){
       if(y%10==9) count++;
       y=y/10;
   }
   if(count==2) cout<<a<<endl;
}
return 0;
}

但我不明白为什么这不起作用。如果我更改它并以这种方式编写它就可以工作。

int main(){
int a, n, i, count, y;
cin>>n;
for(i=1; i<=n; i++){
             count=0;
    cin>>a; y=a;
    while(y>0){
       if(y%10==9) count++;
       y=y/10;
   }
   if(count==2) cout<<a<<endl;
}
return 0;
}

如果您向我解释这一点,将不胜感激。

只需读取为字符串(或将其转换为)并计数:

for(i=1; i<=n; i++){
   std::string numstr;
   std::cin >> numstr; 
   if( std::count( numstr.begin(), numstr.end(), '9' ) == 2 )
      std::cout << numstr << std::endl;
}

如果您没有每次通过主循环将count重置为 0,则会将新数字中的计数添加到前一个数字的计数中。

因此,如果键入 19 作为第一个数字,则将count设置为 1 。然后,如果您为第二个数字键入 939,它将count设置为 3 ,并且测试if (count == 2)将不会成功,即使该数字中有 2 个 9。在此之后,count永远不会成为2,因为您会不断添加它。

您需要从头开始计算每个数字。

请注意,您的算法不适用于负数。 -9 % 10-9,而不是9

我们需要为每种情况初始化count=0