【问题标题】:Random number generator with varies conditions. 3 digits具有不同条件的随机数生成器。 3 位数
【发布时间】:2017-08-13 20:57:35
【问题描述】:

您好,我正在研究一个随机数生成器,但我遇到了障碍。我已经完成了我的程序,但我对如何为 C++ 程序执行循环以继续循环感到很迷茫。以下是程序的条件:

  1. 程序提示用户输入一个数字。
  2. 这个数字决定了循环重复的次数。数字范围从 0 到 100。验证此范围。
  3. 程序使用一个随机数生成一个从 0 到 9999 的数,然后 检查生成的数字是否包含数字 1、数字 2 或数字 3。

请告知我需要如何为第 3 点执行 switch 或 while 循环。 非常感谢您的意见。

【问题讨论】:

  • 什么语言?
  • C++ 兄弟.. 抱歉现在在前面的程序中声明。

标签: random


【解决方案1】:

最简单的检查方法是使用 mod 运算和除法来提取每个数字。

循环类似于

int randInt = randomFunction();
while(randInt > 0){
  //Get Last Digit
  int lastDigit = randInt % 10;

  switch(lastDigit){
    case 1:
    // do something
    break;
    case 2:
    // do something
    break;
    case 3:
    // do something
    break;
  }

  /* 
   Divide the number by 10 to remove the last digit.
   Integers will automatically truncate remainders.
   i.e int a = 21/10, a will = 2 
  */
  randInt /= 10;

}

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 2021-12-31
    • 2020-11-20
    • 2019-04-25
    • 2016-01-12
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多