【发布时间】:2017-10-20 10:13:44
【问题描述】:
我正在用 C++ 编写代码,其中必须完成以下操作 - 创建用户想要的变量数量。这是代码
#include <iostream>
using namespace std;
int main(){
cout<<"how many variables do you want to enter"<<endl;
int numVar;
cin>>numVar;
int i=0;
while(i<numVar){
i++;
static int termi;
// creates 'numVar' number of terms
cout<<"enter term"<<i<<endl;
cin>>termi;
//the user gives values of each term
}
// I want to cout all the terms here and do some calculations
return 0;
如何在循环外使用创建的变量? 我已登录 -learncpp.com,但找不到满意的答案。
【问题讨论】:
-
您不能在运行时创建具有新名称的新变量。改用容器。
-
在你需要的范围内声明变量。如果要访问
main()中和循环外的变量,请在main()内但在循环外定义它们。声明static不会使其名称在其封闭范围之外可访问。
标签: c++ variables while-loop scope