编译错误呢?(c++)

Compiling Error? (C++)

本文关键字:c++ 错误 编译      更新时间:2023-10-16

我对c++非常陌生,我刚刚写了这段代码,它要求你输入,它成为变量,经过计算,并给出一个输出。我得到编译错误,说'int ns'和'int sum'无效。

#include <iostream>
    int main () {
        sum = ns - 2 * 180;
        std::cout << "Enter the number of sides";
        int ns;
        int sum;
        std::cin >> ns;
        sum = ns * 180 - 360;
        std::cout << "The sum of all of the interior angles is" << sum;
        system("PAUSE");
    }
谁能告诉我哪里不对?

在使用标识符之前,您必须定义它。编译器不知道标识符sum和ns在这段代码

中的含义。
int main () {
    sum = ns - 2 * 180;

而且ns还没有初始化。

似乎你应该简单地删除这两个语句

   sum = ns - 2 * 180;
   std::cout << "Enter the number of sides";

程序看起来像

#include <iostream>
#include <cstdlib>
int main () {
    int ns;
    int sum;
    std::cin >> ns;
    sum = ns * 180 - 360;
    std::cout << "The sum of all of the interior angles is " << sum << std::endl;
    system("PAUSE");
}

您试图在定义sumns之前使用它们。

定义nssum,然后使用它们

例如:

int ns;
int sum;
//take input etc.
sum = ns - 2 * 180;
..............