Jump to content
  • Advertisement
Sign in to follow this  
Bladelock

help with exponents

This topic is 2827 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

how would i use the pow() function for helping me create a random number with its maximum number of digits pre-determined by the user.

my code is like this




#include <iostream>
#include <time.h>
#include <cstdlib>
#include <cmath>
using namespace std;

int main()
{
int digits;
int number;

cout << "insert max number of digits random number will have" << "\n";
cin >> digits

number =(rand()% pow(10,digits))+1;
//* above is the line of code where i'm having issues *//

cout << number;

return 0;

}



how exactly do you use pow here? any help is appreciated. thanks!

Share this post


Link to post
Share on other sites
Advertisement
Why the '+ 1'?

Suppose you want 2 digits, let's try a few cases:
(12345 % 100) + 1 = 46 - fine
(12300 % 100) + 1 = 1 - is '0' an invalid random number? You'll never get it.
(12399 % 100) + 1 = 100 - too many digits!

Share this post


Link to post
Share on other sites
Quote:
Original post by Mantear
Why the '+ 1'?
(12300 % 100) + 1 = 1 - is '0' an invalid random number? You'll never get it.


my intention was to get 1-100, which means, i intended to never get 0 as a random number

Share this post


Link to post
Share on other sites
A few things:
1). the line "cin >> digits" needs an ending semicolon.
2). the function pow() does not return an int but rand() requires an int, so you need an explicit cast to int; put (rand()%(int)pow(10,digits))+1
3). include the line "srand(time(NULL));" before calling rand() or you'll get the same number every time.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!