【问题标题】:c++ function input error [closed]c ++函数输入错误[关闭]
【发布时间】:2017-11-21 10:37:30
【问题描述】:

我正在编写一个蒙特卡洛模拟,我的第一个函数是一个输入,但它不断返回一个错误,指出变量“未在此范围内声明”,我尝试在 main 中添加变量类型,它仍然不建立。然后我在函数中添加了变量类型(cin>>rounds 到 cin>> int rounds),错误发生了变化但仍然不起作用。谁能告诉我发生了什么以及我需要做什么才能使该功能正常工作。

#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>

int getInput();
using namespace std;

int main (void){
    //set up random
    srand(time(NULL));

    //1st function
    getInput();

}

/* @description gets a valid user input
* @param output and input
*/
    int getInput(){
        cout<<"enter amount of rounds";
        cin>> rounds; **(error is here on line 24 ("rounds not declared in 
this scope")**
}

【问题讨论】:

  • 我不敢相信你真的忘了声明变量,因为那很明显。可能是你忘了在你的问题中提到它吗?如果你真的忘记了,那可以解释为什么找不到它。
  • 请不要发布错误的解释部分;那没用。发布整个内容,包括编译器为您提供的行号和列号。我投票决定关闭它,因为它没有包含足够的信息来形成有用的答案,因为您没有显示任何关于您正在编译多少文件以及如何编译等的迹象。

标签: c++ function input


【解决方案1】:

“未在此范围内声明”

这意味着您尝试使用变量的位置(即rounds)是未知的。在main 内声明它没有帮助,因为getInput 的范围!= main 的范围。

你有 4 种可能性:

  1. main 中声明并作为参数发送[将在main + getInput 的范围内]
  2. getInput 内声明[将在getInput 的范围内]
  3. 声明为全局(即高于main[将在所有人的范围内]
  4. 添加extern 并在您喜欢的任何地方声明[将适用于所有人]

澄清:“将在...范围内”的意思是“从这里开始...”


这里有代码 sn-ps 来显示你的选择:

/* 1st option */
void foo(int x){
    x = 1;
}

int main()
{
    int x;
    foo(x);
    return 0;
}

/*************************************/

/* 2nd option */
void foo(){
    int x;
    x = 1;
}

int main()
{
    foo();
    return 0;
} 

/*************************************/

/* 3rd option */
int x;

void foo(){
    x = 1;
}

int main()
{
    foo();
    return 0;
}

/*************************************/

/* 4th option */
void foo(){
    extern int x;
    x = 1;
}

int main()
{
    foo();
    return 0;
}
int x;

在我会把你的代码改成这样的:

#include <iostream>
int getInput();
using namespace std;

int main (void){
    ...
    int in = getInput();
    ...
}

/* @description gets a valid user input
* @param output and input
*/
    int getInput(){
        int rounds;
        cout << "enter amount of rounds";
        cin >> rounds; 
        return rounds; // dont forget to return :)
}

【讨论】:

  • 太好了 - 谢谢 - 非常清楚
【解决方案2】:

您需要在函数中声明变量(如 int 或 long 任意所需),如下所示:

int getInput(){
        int rounds;
        cout<<"enter amount of rounds";
        cin>> rounds; **(error is here on line 24 ("rounds not declared in 
this scope")**
}

【讨论】:

  • 非常感谢。
  • 如果没问题 - 请点击答案上的勾号按钮接受答案。谢谢
  • @BabyGroot 你的函数实现可能会导致程序崩溃。
  • @user0042:您能否详细说明正确的方法是什么,因为这可能是修复此代码的基本答案。
  • @BabyGroot 这个函数返回什么? **(error is here on line 24 ("rounds not declared in this scope")** 也根本无法编译。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
  • 1970-01-01
  • 2011-11-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-26
相关资源
最近更新 更多