我用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;
}
请帮我找到并解决。 谢谢。
您需要与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