为什么我在这里得到垃圾(不需要的)输出? [英] Why I am getting garbage(unwanted) output here?
问题描述
每当我编写下面的代码时,都会在某些在线编译器中得到垃圾(意外)输出,但是如果我使用代码块,则会得到满意的输出。 所以我的问题是为什么我得到这种类型的输出?
Whenever I am writing this following code, I am getting garbage(unexpected) output in some online compiler, but if I use code block then getting satisfied output. So my question is why I am getting this type of output?
例如,如果我输入
5 7
+ 5
- 10
- 20
+ 40
- 20
然后我得到
22 1
在代码块中。
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int have, n, i;
int kid=0;
cin>>n>>have;
int line[n];
for(i=0;i<n;i++)
{
cin>>line[i];
if(line[i]>=0)
have+=line[i];
else
{
if(have>=abs(line[i]))
have+=line[i];
else
kid++;
}
}
cout<<have<<" "<<kid<<endl;
}
推荐答案
主要我在您的代码中看到的问题是这样的:
The main problem I can see in your code is this:
int line[n];
这被称为 VLA (可变长度数组),C ++不支持。它在C中有效。由于C ++基于C,但大多数编译器仍允许此行为,但它不是有效的C ++代码。在上一个问题中,我发现clang支持指定的初始化程序,而gcc和vc ++不支持。原因是因为某些编译器(例如clang)默认支持c99扩展名。我的观点是仅仅因为代码可以编译,并不意味着它总是正确的。
This is known as a VLA (Variable Length Array) and it is not supported in C++. It is valid in C. Most compilers still allow this behaviour due to the fact that C++ is based on C, but it is not valid C++ code. In a previous question, I found out that clang supports designated initializers, when gcc and vc++ did not. The reason is because some compilers like clang, support c99-extensions by default. My point is that just because the code compiles, it doesn't mean it's always right.
如果使用 -pedantic
参数,您将看到编译器警告您这是C99功能。在此处中查看示例。从下面的注释中,在编译器标志中使用 -pedantic-errors
,将提示错误。
If you compile with the -pedantic
argument, you will see that the compiler is warning you about this being a C99 feature. Have a look at the rextester example here. From the comments below, using -pedantic-errors
in the compiler flags, will prompt an error.
如果在运行时知道数组的大小,则应该使用静态数组 int line [4];
,但如果不这样做,则需要使用动态数组。 std :: vector本质上是一个动态数组,还可以为您处理内存。易于使用且非常高效。 std :: vector< int>行;
If you know the size of the array before run-time, then you should use a static array int line[4];
, but if you don't then you need to use a dynamic array. std::vector is essentially a dynamic array that also handles memory for you. It's easy to use and very efficient. std::vector<int> line;
您可以在此处详细了解矢量容器: http://www.cplusplus.com/reference/vector/vector/
You can read more about the vector container here: http://www.cplusplus.com/reference/vector/vector/
Btw,我在rextester,ideone和repl.it中尝试了您的代码,得到了相同的结果: 22 1
。我认为您正在目睹它的不确定行为。
Btw, I tried your code in rextester, ideone and repl.it and I got the same results: 22 1
. I think what you are witnessing it undefined behaviour.
此外,您还可以将<$ c $ int in 限定为 constexpr
会没事的。
Also, you can qualify int n
with constexpr
and it'll be fine.
constexr int n = 200;
int line[n]; //now it's ok.
但这再次意味着您在编译时就知道数组的大小。
But this again means that you know the size of the array at compile time.
这篇关于为什么我在这里得到垃圾(不需要的)输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!