gpt4 book ai didi

c++ - 为什么someNumber = rand()&100 + 1;不会产生错误?

转载 作者:行者123 更新时间:2023-12-02 11:07:59 26 4
gpt4 key购买 nike

I was attempting to generate a random number between (1 - 100), and the code to ran, but not doing what I wanted. I noticed I accidentally type &, instead of % with the rand() function, and the compiler did NOT give me an error. What exactly is going on? Why was no error generated? Is the & returning an address? This bug was tricky to find because it's a simple typo that's easy to miss.

Here is the typo:

unsigned int randomNumber = rand() & 100 + 1;

But this is what I mean to type:

unsigned int randomNumber = rand() % 100 + 1;

Here is the code using rand() with & in case you wish to run it:

#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
srand(static_cast<unsigned int>(time(nullptr)));
unsigned int randomNumber;
char again;

do
{
std::cout << "Do you want to generate a random number? (y/n) ";
std::cin >> again;
randomNumber = rand() & 100 + 1;
std::cout << randomNumber << '\n';
} while (again == 'y');


getchar();
return 0;
}

最佳答案

这是bitwise and operator。它需要两个数字,然后“与”它们的位。

例如:3 & 102

 0011
&1010
----
0010

关于c++ - 为什么someNumber = rand()&100 + 1;不会产生错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com