c++ - 小投入,大产出?

标签 c++

我对我写的这段短代码有疑问:

#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

int main() {
    ofstream fout("hps.out");
    ifstream fin("hps.in");
    int N;
    fin >> N;
    int a1, a2, b1, b2, c1, c2 = 0;
    for (int i = 0; i < N; i++) {
        int x, y;
        fin >> x;
        fin >> y;

        if (x == 1 && y == 2) {
            a1++;
        }
        if (x == 1 && y == 3) {
            a2++;
        }
        if (x == 2 && y == 1) {
            b1++;
        }
        if (x == 2 && y == 3) {
            b2++;
        }
        if (x == 3 && y == 1) {
            c1++;
        }
        if (x == 3 && y == 2) {
            c2++;
        }
    } 
    fout << a1 << " " << a2 << " " << b1 << " " << b2 << " " << c1 << " " << 
c2 << " " << '\n';
    return 0;
}

所以这是输入:

5
1 2
2 2
1 3
1 1
3 2

这是输出:

32768 4197767 0 616536480 0 1

我想做的是计算 (1,2)、(1,3)、(2,1)、(2,3)、(3,1) 和 (3,3) 的对数, 并将这些值存储在变量 a1, a2, b1, b2, c1, c2 中。但是由于某种原因,我得到了这些巨大的数字,但我不明白为什么。有什么东西溢出来了吗?

这个问题的陈述实际上是 USACO Bronze Janurary #2:

http://www.usaco.org/index.php?page=viewproblem2&cpid=688

如有任何帮助,我将不胜感激!

最佳答案

问题在于这一行:

int a1, a2, b1, b2, c1, c2 = 0;

这只会用零初始化 c2。其余的持有垃圾值。 您需要为每个变量执行 = 0

关于c++ - 小投入,大产出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48304930/

相关文章:

c++对象的虚函数调用

c# - 如何将带有 unsigned char* 的结构从 C# 传递到 C++?

c++ - atexit() 处理程序中的 Windows 获取由::exit() 设置的当前进程退出代码

c++ - 为返回 C++/.NET 老手学习 Boost 的最快方法

c++ - 这段 C++ 代码有什么问题?

c++ - 我需要使用 'using namespace std' 命令吗?

c++ - Qt 用户调整大小事件结束(stops)

c++ - 原生显卡功能

c++ - 我不明白 --- int x = 0;整数 y = 2; int z = (++x,++y);

c++ - 确定for循环的不同大O复杂度