gpt4 book ai didi

c++ - 检查数字中的奇数位

转载 作者:太空宇宙 更新时间:2023-11-04 13:11:07 25 4
gpt4 key购买 nike

我正在尝试编写一个程序来检查一个数字中的所有数字是否都是奇数,但是表示该数字仅由奇数组成的 cout 仅在输入的数字为 1 位长时才显示。这是代码:

int main()
{
int n, c;
cin >> n;
while (n != 0) {
c = n % 10;
if (c % 2 == 1) {
n = n / 10;
if (n == 0) {
cout << " Number has only odd digits";
}
}
else
cout << " Number doesn't have only odd digits";
return 0;
}
}

最佳答案

我建议将数字保留为字符串,然后在字符串中搜索奇数:

static const char odd_digits[] = "13579";
std::string number_as_text;
std::cin >> number_as_text;
std::string::size_type position;
position = number_as_text.find_first_of(odd_digits);
if (position != std::string::npos)
{
std::cout << "Number has at least one odd digit.\n";
}

作为字符串的数字从奇数位列表中搜索任何字符。

关于c++ - 检查数字中的奇数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39879915/

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