我的作业要求我们两次生成一个三位数字,以便学生将它们加在一起,然后检查他们的工作。我对C ++仍然非常非常新,我的课程遗憾地没有提供有关如何做到这一点的信息。他没有提供随机生成数字的视频,文章或任何内容,如何保护特定数量的数字,甚至不提供如何将它们组合在一起。
以下是我拼凑在一起的代码,原样粗糙。我不能保证三位数。时不时地,它将是一个两位数的数字。我已经给他发了电子邮件,看他是否能指出我正确的方向,但我并不乐观。我想我会设置一个最小值,但经过几个小时的搜索,我找不到答案。
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std; //This is so I do not have to type std::
int main(void)
{
int set1;
int set2;
int sum=0;
srand((unsigned) time(NULL)); // sets the random seed to provide different number utilizing the time of the computer
set1 = rand() % 999 + 1; //creates a randomly generated three digit number
set2 = rand() % 999 + 1; //created a randomly generated three digit number
cout << "\n\n\n Are you ready for some math practice?\n\n\n";
cout.width(8); //sets width of the columns to align everything
cout << set1 << "\n"; //prints first generated set
cout << " + ";
cout << set2 << "\n"; //[rints second generated set
cout << "---------\n";
cout << "\n\n\n";
sum = set1 + set2; //add the two generated sets together
cout << "Try to solve the problem. Have you got it?\n";
system("Pause"); //waits for student to press enter to continue
cout << "\n\n\n";
cout << "The answer is: ";
cout << sum; //displays sum of two numbers
答案 0 :(得分:3)
这就是你正在使用的。您需要三条信息:
要以C方法计算它,计算除以范围的余数并添加最小值。那就是:
set1 = rand() % 900 + 100;
任何数字模数900都会给你一个0..899的值。加100,你得到一个100..999的数字。瞧!
上述方法存在偏差(感谢Pigeonhole Principle)。修复它的方法是简单地拉随机数,直到你得到一个在所需范围内:
int random_in_range( int minimum, int maximum )
{
int result;
do result = rand();
while (result < minimum || maximum < result);
return result;
}
现在您可以简单地询问您想要的号码:
set1 = random_in_range( 100, 999 );
唯一需要注意的是非常小的范围(如0..3)可能会产生明显的滞后;你会希望对此更加复杂一点。 (例如在0..399中询问数字并除以100。)
由于您使用的是C ++,因此您也可以学习如何正确地使用它。
#include <chrono>
#include <random>
int random_in_range( int minimum, int maximum )
{
thread_local std::ranlux48 rng(
std::chrono::system_clock::now().time_since_epoch().count() );
return std::uniform_int_distribution <int> ( minimum, maximum )( rng );
}
...
set1 = random_in_range( 100, 999 );
这里我们使用静态(线程安全 - 如果你只有一个线程只使用单词static
而不是thread_local
)伪随机数生成器,我们使用它得到一个数字由所需的最小值和最大值给出的范围内的均匀整数分布。
它全部包含在一个方便的函数中,因此在使用它时看起来与C版本相同,但它在以下方面更好:
您可以以相同的方式使用现有代码:生成两个随机的三位数字,要求用户输入他们的总和并将其答案与您的答案进行比较。
答案 1 :(得分:2)
你非常接近!
set1 = rand() % 999 + 1; //creates a randomly generated three digit number
这实际上会在1
和999
之间生成一个随机数。您想要的是生成100
和999
之间的数字,最简单的方法是生成0
和899
之间的数字,然后添加{{ 1}}:
100
set1 = rand() % 900 + 100; //creates a randomly generated three digit number
适用于您的目的,但您可以使用uniform_int_distribution
rand()