【问题标题】:Sum of negative and positive integers leads to unexpected output - c++负整数和正整数之和导致意外输出 - C++
【发布时间】:2021-10-28 13:13:18
【问题描述】:

我有一个二维数组,愿意检查(每)列的总和是否为 0。此外,从数组中添加整数似乎会导致意外输出。

#include<bits/stdc++.h>
using namespace std;
int main() {
long long int lines;
int temp;
int is_0 = 1;
cin>>lines;
int numbers[3][lines];
for(int i = 0; i < 3; i++){
    for(int j = 0; j < lines; j++){
        cin>>temp;
        numbers[i][j]=temp;
    }
}

for(int i = 0; i<3; i++){
    temp = 0;
    for(int j = 0; j<lines;j++){
        temp += numbers[i][j];          
    }
    cout<<temp<<endl;
}
return 0;
}

示例输入:

2
1
1
1
-1
-1
-1

示例输出:

2
0
-2

有什么想法吗?

【问题讨论】:

  • 听起来您可能需要学习如何使用调试器来单步调试您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programsDebugging Guide
  • 这并没有解决问题,但是代码在输入循环中不需要tempstd::cin &gt;&gt; numbers[i][j]; 工作得很好。
  • 画图;当代码读取输入时,哪些值去了哪里?在计算总和的循环中,什么值在哪里?提示:lines 这个名称具有误导性。
  • cin&gt;&gt;lines; int numbers[3][lines]; 看起来像一个 VLA。我认为 VLA 在 C++ 中不是标准的。也许这种情况下使用了编译器扩展?

标签: c++ arrays


【解决方案1】:

程序按预期运行。 您正在创建以下矩阵

 1   1
 1  -1
-1  -1

这里

for(int i = 0; i<3; i++){
    temp = 0;
    for(int j = 0; j<lines;j++){
        temp += numbers[i][j];          
    }
    cout<<temp<<endl;
}

你正在总结每一行的数字。

【讨论】:

  • 酷! +1 这显示了验证和验证之间的区别。 . .
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
  • 2017-09-28
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多