C++字符串数组和 for 循环无法按预期工作
C++ string array & for loop doesnt work as i expected
#include <iostream>
using namespace std;
int main()
{
char num[10];
int a;
cout << "Odd or Even"<< endl;
for(;;)
{
cout << "Enter Number:" ;
cin >> num;
cout << endl;
for(a=9;a>=0;a--)
{
if(num[a]!=' && num[a]!=' ')
break;
}
if(num[a]==1 || num[a]==3 || num[a]==5 || num[a]==7 || num[a]==9)
cout << "Odd" << endl;
else
cout << "Even" << endl;
}
}
我是一个c++新手,我写了一个程序来区分一个数字是偶数还是奇数,但无论我输入什么数字,它只输出"偶数"。所以我添加了这些来找出循环何时中断:
cout << a << endl;
cout << """ << num[a] << """ << endl;
结果:<>之前输入号码:119"甚至之前 for循环在num[9]=' '
?这将导致else并始终输出"Even"。
您对字符'1'
和数字1
感到困惑。它们是不同的。
代替
if(num[a]==1 || num[a]==3 || num[a]==5 || num[a]==7 || num[a]==9)
你需要 if(num[a]=='1' || num[a]=='3' || num[a]=='5' || num[a]=='7' || num[a]=='9')
还有一个问题可能会把你绊倒。
num
未初始化。Zero-initialize它。请记住,0
和'0'
是不一样的。char num[10] = {0};
将
num
的初始化移动到for
循环中。这将消除先前循环执行的数据影响当前循环执行的问题。
这是一个适合我的版本。
#include <iostream>
using namespace std;
int main()
{
cout << "Odd or Even"<< endl;
for(;;)
{
char num[10] = {0};
int a;
cout << "Enter Number:" ;
cin >> num;
cout << endl;
for(a=9;a>=0;a--)
{
if(num[a]!=' ' && num[a]!=' ')
break;
}
cout << num[a] << endl;
if(num[a]=='1' || num[a]=='3' || num[a]=='5' || num[a]=='7' || num[a]=='9')
cout << "Odd" << endl;
else
cout << "Even" << endl;
}
}
p
可以替换
if(num[a]!=' ' && num[a]!=' ')
if(isdigit(num[a]))
如果你用c++做这个,有更简单的方法!考虑以下内容:
while (!done) {
string inputline;
getline(cin, inputline); //Now we have a string with the users input!
stringstream ss; // stringstreams help us parse data in strings!
int num; // We have a number we want to put it into.
ss >> num; // We can use the string stream to parse this number.
// You can even add error checking!
// Now to check for odd even, what do we know about even numbers? divisable by 2!
if (num % 2 == 0) // No remainder from /2
cout << Even << 'n'
else
cout << Odd << 'n'
}
看看你是怎么做的!
警告未测试代码
这一行你打错了。
if(num[a]!=' && num[a]!=' ')
应该是
if(num[a]!=' ' && num[a]!=' ')
相关文章:
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 循环仅对第一行正常工作.其他行不受 for 的影响
- 当输入在带有空格的单行中给出时,cin 如何在 while 循环中工作?
- C++中循环和 C 样式数组的范围工作
- 为什么我的 while 循环对于特定输入中断,而对于其他输入工作正常?
- 为什么循环没有中断,并且 if 条件没有按预期工作?
- 如何使这个 Foor 循环在这个问题中工作?
- 在矩阵逆变器上工作,由于某种原因,我的指数循环不起作用
- 当循环在条件C++之前停止工作时
- C++-循环中的If语句工作不正常
- 如何修复使用execv和forks无法工作的循环
- 如何使用while循环找到GCD?模数运算符是如何工作的
- While循环和if/else语句工作不正常
- 这个代码片段中的while循环是如何工作的
- 我在循环中的循环中遇到问题,无法正常工作
- for 循环中的线程无法正常工作
- 无限而循环不工作C++
- For 循环使用指针遍历数组无法正常工作
- for (x:y) 循环在 C++ 中无法正常工作
- Gnu_radio,工作循环和停止