[英]c++ test if random number is positive or negative
我有 C++ 的学校作业,我是新来的。 我必须生成 17 个随机数,然后测试它们是否为正/负/等于零。 我似乎无法找到一种方法来从 for 循环中获取随机生成的数字以在 if/else if 循环中对其进行测试。 Heeeeeelp 请:D(b 变量就在测试中)
#include <ctime>
using namespace std;
int main() {
srand(
(unsigned) time(0)
);
int a;
int b;
int num;
for(int a = 0; a<17; a++) {
cout << "Skaitlis: " << rand()% 20 + -10 << "\n";
if(b > 0){
cout << b << " is a positive number." << endl;
}
else if (b == 0){
cout << b << " is equal to zero." << endl;
}
else {
cout << b << " is a negative number." << endl;
}
}
}
很简单,首先将值赋给 b,然后你就可以比较它了。 当前的 cout 只是输出它。
b = rand()% 20 - 10;
cout << "Skaitlis: " << b << "\n";
首先,您的变量b
根本没有任何价值。 在你的循环中,你问了 17 次b
是否大于、小于或等于 0,你的问题在哪里。
你从来没有分配给b
。 您将通过在循环中添加b = rand() % 20 + -10
来修复它。 现在你的b
有一个实际值。
另外,而不是
cout << "Skaitlis: " << rand()% 20 + -10 << "\n";
,
改成
cout << "Skaitlis: " << b << endl;
.
此外,您的cout
不存在,因为它从未声明过。 我想说的是,您的程序中没有cout
function,因为cout
位于“iostream”库中。 您还必须包含“iostream”库,在代码开头使用#include <iostream>
。
澄清:
你的b
没有价值。 在询问 b 是否大于、小于或等于 0 之前先给b
赋值;
cout
未添加到您的程序中。 使用#include <iostream>
包含“iostream”
最终代码可能如下所示:
#include <iostream> // so I can use cout << and cin >>
#include <ctime>
int main() {
int b;
srand(time(NULL)); // NULL is same as 0
for (int a = 0; a < 17; a++) {
b = rand() % 21 - 10; // Assign a value between -10 and +10 to b
if (b > 0) cout << b << "is greater than 0" << endl;
else if (b < 0) cout << b << "is lower than 0" << endl;
else cout << b << "is equal to 0" << endl;
}
return 0;
}
我希望这个解释有所帮助。
您可以使用:
#include <random>
void function(){
std::random_device rd; // obtain a random number from hardware
std::mt19937 gen(rd()); // seed the generator
std::uniform_int_distribution<> distr(-100, 100); // define the range
int randomNumber = distr(gen);
if(randomNumber > 0)
// bigger than 0
else if(randomNumber == 0)
// equals 0
else
// less than 0
}
我不确定这是否是你的意思,但你可以将随机 function 的结果分配给一个变量,例如:
int rnd = rand() % 20 - 10;
cout << "Skaitlis: " << rnd << '\n';
if (rnd > 0)
cout << rnd << " is a positive number." << endl;
else if (rnd == 0)
cout << rnd << " is equal to zero." << endl;
else
cout << rnd << " is a negative number." << endl;
另外,如果您刚刚开始编程,我认为没有必要知道,但请记住rand()
并不是创建随机数的好方法。 最好使用例如mt19937
(虽然它有点复杂)。 rand()
function 最多只能生成 32767 个随机数(尽管它也取决于您使用的编译器),如果您试图获得特定范围内的随机数,那么rand()
function 将返回一个较小的数字。
考虑这个示例代码:
#include <iostream>
#include <string>
bool is_positive(int number)
{
if (number >= 0) return true; // Positive number or 0
else return false; // Negative number
}
int main()
{
std::srand(time(0));
for (int i = 0; i < 17; i++)
{
int number = std::rand() % 20 + -10;
if (is_positive(number))
{
std::cout << number << " is positive" << std::endl;
}
else
{
std::cout << number << " is negative" << std::endl;
}
}
}
在这里,我定义了一个 function is_positive,如果数字大于或等于 0,则返回 true,否则返回 false。 我还展示了 function 的简单实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.