gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
generate a random c+ code.
- User
generate a random c+ code.
- Assistant
Sure! Below is a simple C++ program that generates and prints a random number between 1 and 100.
#include <iostream> #include <cstdlib> // For srand() and rand() #include <ctime> // For time() int main() { // Seed the random number generator with the current time std::srand(static_cast<unsigned int>(std::time(0))); // Generate a random number between 1 and 100 int randomNumber = std::rand() % 100 + 1; // Print the random number std::cout << "Random number between 1 and 100: " << randomNumber << std::endl; return 0; }This program utilizes the
<cstdlib>and<ctime>libraries to generate random numbers. Thestd::srand()function is used to seed the random generator with the current time, ensuring that you get different sequences of random numbers each time you run the program. Thestd::rand()function generates the random number, which is then constrained between 1 and 100 using modulus arithmetic.