修复这个简单的代码

时间:2016-10-14 18:29:22

标签: c++

我是编码的初学者,我无法修复此代码,而且我发疯了。它一直告诉我某些变量没有被声明,我不确定如何修复它。

#include <iostream>

using namespace std;

int main()
{
int (a = 0), sum;{
    cout << "This program should read all integer numbers ";
    cout << "to sum until a negative number is entered\n";
    exit(0);
}

while(a < 0) {
   cout << "Enter an integer number: ";
   cin >> a;
   sum += a;
}

cout << "The sum is sum\n";
return 0;
}

2 个答案:

答案 0 :(得分:4)

你没有初始化总和,所以它可以从任何值开始。

你无缘无故地拥有额外的无意义{ }层。

您的最终cout声明实际上并未打印变量 将其更改为:cout << "The sum is " << sum << "\n";

#include <iostream>

using namespace std;

int main()
{
  int a = 0, sum = 0;
  cout << "This program should read all integer numbers ";
  cout << "to sum until a negative number is entered\n";

  do {
     cout << "Enter an integer number: ";
     cin >> a;
     if (a > 0)
     {
         sum += a;
         cout << "The sum is currently: " << sum << "; but this is not yet the final value.\n";
     }
  } while(a > 0) ;

  cout << "The sum is " << sum << "\n";
  return 0;
}

答案 1 :(得分:-1)

你的代码有很多陷阱。

我发现并纠正的问题:

  • 您有额外的括号和大括号。
  • 您没有初始化名为sum
  • 的变量
  • 您将名为a的变量初始化为0,但您的循环仅在a小于0
  • 时执行
  • 我必须 #include“stdafx.h”,其中包含 iostream
  • 表示“总和为总和”的行 - 第二个总和应该在双引号之外,以便将其视为变量而不是文本。

此代码有效,请与您的代码进行比较:

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()

{
    int a = 0, sum = 0;

    cout << "This program should read all integer numbers ";
    cout << "to sum until a negative number is entered\n";

    while (a <= 0) {
        cout << "Enter an integer number: ";
        cin >> a;
        sum += a;
    }

    cout << "The sum is " << sum << "\n";
    return 0;
}