【发布时间】:2018-02-27 04:33:56
【问题描述】:
我有一个作业要求我们生成一个三位数两次,以便学生可以将它们加在一起,然后检查他们的作业。我对 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到899之间的随机数,然后加100呢?
-
你很接近:
rand() % 999将生成一个介于0和998之间的数字。相反,您可能应该在100和898(rand() % 899 + 100) 之间生成一个数字,然后添加100。有人可能会回答比我写的更好的混搭。
标签: c++