c++ - 获取大的负数打印数组

标签 c++ arrays

你好,我在尝试将一些变量输出到屏幕时得到负值。

我查了一下,在大多数情况下它是一个未初始化的变量,但我找不到任何错误。

说我的代码与文本的比例太多,但我真的不知道如何重申,所以这里有一些填充物。

#include <iostream>
#include <string>

using namespace std;


int main()
{

    int Input;
    int WepType;
    string Weapon;
    string WeaponType;

    int Stats[3];
    int AtkStats[4];


cout << "Pick your weapon.\n" << endl;
cout << "{===================================================}\n";
cout << "[                                                   ]\n";
cout << "[  Iron Longsword              Sharp Fishing Spear  ]\n";
cout << "[         1                                         ]\n";           
cout << "[                                                   ]\n";     
cout << "[              Ornate Hunting Bow                   ]\n";
cout << "[                                                   ]\n";
cout << "{===================================================}\n";

//Weapon Selection
 cin >> Input;

    if(Input == 1)
    {
     WepType     = 1;
     Weapon      = "Iron Longsword";
     WeaponType  = "OneHanded";
     Stats[0]    = Stats[0] + 10;
     Stats[1]    = Stats[1] + 0;
     Stats[2]    = Stats[2] + 0;
     AtkStats[0] = AtkStats[0] + 10;
     AtkStats[1] = AtkStats[1] + 0;
     AtkStats[2] = AtkStats[2] + 0;
     AtkStats[3] = AtkStats[3] + 0;


    cout << "Weapon      = " << Weapon      << endl;
    cout << "Weapon Type = " << WeaponType  << endl;
    cout << "Health      = " << Stats[0]    << endl;
    cout << "Physical    = " << AtkStats[0] << endl;
    cout << "Light       = " << AtkStats[1] << endl;
    cout << "Dark        = " << AtkStats[2] << endl;
    cout << "Temporal    = " << AtkStats[3] << endl;
    }



      return 0;
    }

最佳答案

问题出在这里:

int Stats[3];
int AtkStats[4];

你应该这样做:

int Stats[3] = {0, 0, 0};
int AtkStats[4] = {0, 0, 0, 0};

或者正如 BlastFurnace 在评论中指出的那样(我忘记了):

int Stats[3] = {}; // Initialize all elements to zero.
int AtkStats[4] = {};

为了初始化值。现在它们只是随机的垃圾,所以当你分配时,你会得到错误。

关于c++ - 获取大的负数打印数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45070524/

相关文章:

c++ - 在不同解决方案中的同一项目上单独#define

c++ - Opengl 渲染到具有部分透明度(半透明)的纹理,然后将其渲染到屏幕

javascript - JSONArray 创建后出现额外的数字

javascript - 文本框使用键搜索数组并显示最接近的结果

java - 检查字符串是否包含确切的关键字

c++ - 在 MinGW 中导入内联函数

c++ - 绘制凸面缺陷 C++ OpenCV

c# - 调试执行路径中缺少 msvcr100d.dll 和 msvcp100d.dll

c# - 为什么数组大小声明使用 "1"作为第一个索引?

c - 如何将空白数组排序到顶部以便我可以删除它们