提问者:小点点

为什么这个C++代码没有正确计算?


我用C++写了一段代码来计算零。 输入必须作为字符串。 输入将是一个带1和0的数字。

示例:

输入:1000000001输出:8

答案应该是8,但我的代码显示的是0。 代码中的问题在哪里。

代码:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string players;
    cin >> players;
    int count = 0;
    for (int j = 0; j < players.length(); j++)
    {
        if (players[j] == 0)
        {
            count++;
        }
    }
    cout << count;

    return 0;
}

请帮我找到并解决。 谢谢。


共3个答案

匿名用户

您需要与char而不是int:

if (players[j] == '0')

匿名用户

如果玩家的条件[j]==0错误,则在尝试与整数类型0进行比较时,您的输入是字符串类型。 正确的if检查是players[j]=='0'。 使用bits/stdc++.h使用名称空间std;在C++中是一个很大的否定。

#include <iostream>
#include <string>

int main()
{
    std:: string players;
    std:: cin >> players;
    int count = 0;
    for(const char &player : players)
    {
        if (player == '0')
        {
            count += 1;
        }
    }
    std:: cout << count;

    return 0;
}

匿名用户

条件不对。 编写类似于

players[j] == "0"

你的情况意味着

player[j] == NULL

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|代码|计算)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?