c++ - 返回值错误

标签 c++

所以我正在创建一个随机数生成器,但我不断遇到问题。在我的程序中,我将代码打印到“int main()”函数中。问题是它之后打印了 0。它还说我必须使用 return,但我不想这样做。我想将随机数生成器保留在另一个函数中,因为我将来会添加更多。

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

using namespace std;

int randRoll();

//Calls the other function
int main()
{
    cout << randRoll() << endl;

    system("Pause");
}

//Gets the random number
int randRoll()
{
    srand(time(0));

    for (int x = 1; x <= 1; x ++)
    {
        cout <<"Your random number is " << 1 +(rand()%4) << endl;
    }

    return 0;
}

最佳答案

试试这个:

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

using namespace std;

int randRoll();

// entry point
int main()
{
    srand(time(0));     // initialize randomizer

    cout << randRoll() << endl;

    system("Pause");

    return 0;
}

//Gets the random number
int randRoll()
{
    auto x = 1 +(rand()%4);

    // do something with x here (but don't call cout!)

    return static_cast<int>(x);
}

您遇到的问题是您没有返回随机生成的值(我在代码中将其称为x)。另外,您尝试两次打印随机生成的值(但错误)。

关于c++ - 返回值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20441088/

相关文章:

c++ - 无法使用 CUDA + MATLAB + Visual Studio 检查全局内存

c++ - 使用Microsoft安全支持提供程序接口(interface)(SSPI)加密和签名消息

c++ - 为什么enable_shared_from_this必须公开继承?

c++ - 创建 Windows 窗体控件 (C++)

c++ - 如何将 Python 编译成 C++ .exe

c++ - 恒定值变化

c++ - C类继承B类和A类,B类也继承A类

c++ - 汉诺塔

c++ - 必须将c++中的十六进制文件加载到缓冲区中?

c++ - 如何将 char 和 int 存储在同一个变量中?