我正在尝试制作一个程序,检查一个数字中的所有数字是否都是奇数,但只有当输入的数字是1位数时才会显示该数字仅由奇数位组成的cout。 这是代码:
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;
}
}
答案 0 :(得分: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";
}
从字母列表中搜索任何字符作为字符串。
答案 1 :(得分:0)
我做了很少的改动,以保留你原来的思想流。 n=n/10
需要在else
个案例中执行input as 0
。添加了对return(0)
案例的处理。当您检测到偶数位时添加了int main() {
int n, c;
cin >> n;
if (n==0) {
cout << "Number is zero. So it doesn't have only odd digits" << endl;
return(0);
}
while (n != 0) {
c = n % 10; n = n / 10;
cout << "n=" << n << " c=" << c << endl;
if (c % 2 == 1) {
if (n == 0) {
cout << "Number has only odd digits" << endl;
}
}
else {
cout << "Number doesn't have only odd digits" << endl;
return(0);
}
}
return(0);
}
语句(继续没有任何意义,因此从那里返回)。
SELECT *
FROM table_name
WHERE event IN ( 37, 49 )
AND ename NOT IN(SELECT DISTINCT( ename )
FROM table_name
WHERE date IS NOT NULL)
UNION
SELECT *
FROM table_name
WHERE event NOT IN ( 37, 49 )
AND ename NOT IN(SELECT DISTINCT( ename )
FROM table_name
WHERE date IS NOT NULL);
答案 2 :(得分:0)
你的问题是这些问题:
else
cout << " Number doesn't have only odd digits";
return 0;
编译器将其解释为:
else {
cout << " Number doesn't have only odd digits";
}
return 0;
这意味着无论return
是奇数还是偶数,它总是执行c
。要解决此问题,请在else子句中添加显式大括号:
else {
cout << " Number doesn't have only odd digits";
return 0;
}
这种错误就是为什么大多数样式指南要求您在if
和else
之后始终使用大括号,即使只有一行。