gpt4 book ai didi

c++ - 为什么输入后得到随机数?

转载 作者:太空宇宙 更新时间:2023-11-04 15:18:33 25 4
gpt4 key购买 nike

我正在尝试接受一些输入并查找字符串中特定字符的数量。当我尝试输入实际的字符串时,我总是得到一个奇怪的答案。为什么会这样?我正在使用 cout 来查找为什么我得到如此奇怪的数字,这似乎是输入问题。

注意 - 这是我对 Codeforces 问题 462 B 的尝试解决方案。我试图在输入中找到特定字母的编号。我的 friend 正在尝试一种冒泡排序方法。

输入:

6 4
YJSNPI

预期输出:

YJSNPI
4

实际输出:

YJSNPI
1699623981

代码:

#include <iostream>
#include <string>
#include <vector>
#include <istream>

using namespace std;

int main()
{
int n, k, counting;
cin >> n >>k;
char trash;
cin.get(trash);
vector<string> cards;
string theline, name;
cin >> theline;
cout << theline << "\n";
for (int i = 0; i < n; i++){
name = theline[i];
cards.push_back(name);
}
for (int i = 0; i < n; i++){
if (cards[i] == cards[k-1]){
counting++;
}
}
int tmp = 0;
if (cards.size() != k){
tmp = k - counting;
}
counting *= k;
counting += tmp;
cout << counting;
return 0;
}

最佳答案

局部变量不会自动初始化为 0。如果您在分配之前尝试使用局部变量的值,则会出现未定义的行为。您正在递增 counting 而未对其进行初始化。更改为:

int n, k, counting = 0;

关于c++ - 为什么输入后得到随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25559795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com