找到其中正好有 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
。
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 在将数字随机生成为数组期间从内存输出随机数的数组