【问题标题】:How to use randomly generated number in switch statement?如何在switch语句中使用随机生成的数字?
【发布时间】:2015-09-14 10:31:12
【问题描述】:

我正在制作一个简单的程序,从我在 switch 语句案例中编写的句子中显示人的行为。我想随机生成一个介于 1 到 10 之间的数字并在“switch(this place)”中使用它。到目前为止,我已经编写了以下代码并卡在这里..

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int rand_range(int low, int high)
{
  return rand()%(high-low) + low;
}
int main()
{
    srand(time(NULL));
    cout<<"Hi!, this program tells you about your behaviour"<<endl;
    cout<<"press enter to continue";
    cin.get();

    switch(    )
    {
    case 1:
        {
            cout<<"you are rude !";
        }
    case 2:
        {
            cout<<"you are smart";
        }
    case 3:
        {
            cout<<"you try to prove yourself special all the time";
        }
    case 4:
        {
            cout<<"you are good in sarcasm";
        }
    case 5:
        {
            cout<<"you look dumb, but deep inside you are intelligent";
        }
    case 6:
        {
            cout<<"you are always ready for a debate with someone";
        }
    case 7:
        {
            cout<<"you are very lazy";
        }
    case 8:
        {
            cout<<"you are dumber than what you look";
        }
    case 9:
        {
            cout<<"you always try to help others";
        }
    case 10:
        {
            cout<<"you have good decision making capabilities";
        }
    default:
        {
            cout<<"something wrong";
        }
    }
}

【问题讨论】:

  • 有什么问题?

标签: c++ random switch-statement ctime


【解决方案1】:

在您想要(rand() % 10) + 1 的括号中的switch 语句中。为随机数生成器播种后,rand() 函数将返回一个介于 0 和 RAND_MAX 之间的数字。 RAND_MAX 是一个很大的数字。

要获得一个范围内的随机数,标准技巧是使用% 运算符。 rand() % 10 返回一个介于 0 和 9 之间的数字。加 1 得到 1 到 10 的范围。

【讨论】:

  • 谢谢!但现在我的 switch 语句失败了
  • @PrakharShukla:你需要附加一个中断;在您的每个案例结束时。
猜你喜欢
  • 2016-05-08
  • 2016-09-19
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多