我如何找到零

时间:2018-01-23 15:29:48

标签: c++

我已经获得了一项任务,可以查找用户输入的数字的所有均值,赔率和零。我已经找出了几乎所有的代码,但我无法弄清楚它为什么不打印出来零的数量。任何人都可以尝试解释为什么会这样吗?谢谢。

    #include <iostream>
    #include <cmath>
    #include <array>
    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    using namespace std;
    int main() {
        string stringToGuess;
        cout << "Hello user would you please enter a long number." << endl;
        cin >> stringToGuess;
        int arrLength = stringToGuess.length();
        int odd = 0;
        int even = 0;
        int zero = 0;
        char cho;
        char length = stringToGuess.length();
        char arrToGuess[arrLength];
      for (int i = 0; i < arrLength; i++){
        arrToGuess[i] = stringToGuess[i];
      }
      for (int a = 0; a < arrLength; a++){
        if (arrToGuess[a] == 0) {
          zero = zero + 1;
          cout << "ZERO";
        }
        if (arrToGuess[a] != 0 ){  
          if (arrToGuess[a] % 2 == 0) {
            even = even + 1;
            cout << "Even"; 
          }
          if (arrToGuess[a] % 2 != 0){
            odd = odd + 1;
            cout << "Odd";
          }
        }
      }
      cout << "Odd Numbers = " << odd << endl;
      cout << "Even Numbers = " << even - zero << endl;
      cout << "Zeros = " << zero << endl;
      cout << "Total = " << arrLength << " Numbers" << endl;
    }

3 个答案:

答案 0 :(得分:2)

您无法找到零,因为您实际上是在测试符号而不是实际数字,因为您的输入是一串文本。符号'0'实际上是ASCII表中的代码48,因此如果您测试if (arrToGuess[a] == 0)它将永远不会成立。

改为使用if (arrToGuess[a] == '0')

其他数字起作用,因为巧合的是,赔率和偶数的代码也是赔率和均衡。

答案 1 :(得分:0)

伊戈尔回答了你的问题。您需要将字符转换为整数值,例如与std :: stoi。

你的代码适用于1-9,因为ascii的赔率恰好是奇数,而evens恰好是偶数。零有一个偶数编码,所以我假设你正在计算一个额外的偶数。

答案 2 :(得分:0)

出现的第一个问题是字符0不等于整数0

0!='0'

如果你真的想要这个代码工作,你应该使用48而不是0,其余人已经得到了回答。如果您希望代码能够运行,那么这就是代码。

从0到48的简单替换工作。

#include <iostream>
#include <cmath>
#include <array>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
int main() {
    string stringToGuess;
    cout << "Hello user would you please enter a long number." << endl;
    cin >> stringToGuess;
    int arrLength = stringToGuess.length();
    int odd = 0;
    int even = 0;
    int zero = 0;
    char cho;
    char length = stringToGuess.length();
    char arrToGuess[arrLength];
  for (int i = 0; i < arrLength; i++){
    arrToGuess[i] = stringToGuess[i];
  }
  for (int a = 0; a < arrLength; a++){
    if (arrToGuess[a] == 48) {
      zero = zero + 1;
      cout << "ZERO";
    }
    if (arrToGuess[a] != 0 ){  
      if (arrToGuess[a] % 2 == 0) {
        even = even + 1;
        cout << "Even"; 
      }
      if (arrToGuess[a] % 2 != 0){
        odd = odd + 1;
        cout << "Odd";
      }
    }
  }
  cout << "Odd Numbers = " << odd << endl;
  cout << "Even Numbers = " << even - zero << endl;
  cout << "Zeros = " << zero << endl;
  cout << "Total = " << arrLength << " Numbers" << endl;
}