C++字符串数组和 for 循环无法按预期工作

C++ string array & for loop doesnt work as i expected

本文关键字:工作 循环 字符串 数组 for C++      更新时间:2023-10-16
#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')

还有一个问题可能会把你绊倒。

  1. num未初始化。Zero-initialize它。请记住,0'0'是不一样的。

    char num[10] = {0};
    
  2. 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]!=' ')