By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,666 Members | 1,909 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,666 IT Pros & Developers. It's quick & easy.

Generate a random number then use that to divide the user input number

P: 64
Like the titles says I'm suppose to generate a random number then divide that by a number inputed by a user. The random number can range from 2-8. I tried to do the code, but I get some weird result here is the result

Expand|Select|Wrap|Line Numbers
  1. Please enter a number:  18
  2. a. number                         18.00
  3. b. the random number              6
  4.    00-1.#J << suppose to be 3 , but I get this number. (Trying to get 18 divided by 6.
  5.  
This is the code I have so far.

Expand|Select|Wrap|Line Numbers
  1. int main (void)
  2.  
  3. {
  4. //    Local Declarations 
  5.     double number;
  6.     float result;
  7.     float random = 2 + rand()%8;
  8.  
  9. //    Statements 
  10.     printf("Please enter a number:");
  11.     scanf("%lf", &number);
  12.     srand(time(NULL));
  13.  
  14.  
  15.  
  16.     printf("a. number\t\t\t %5.2lf\n", number);
  17.     printf("b. the random number\t\t  %d\n", rand() % (int)random + 2);
  18.     result = number / random;
  19.     printf(" the result is %5.2lf", result);
  20.  
  21.  
Thanks in advance!
Jan 31 '07 #1
Share this Question
Share on Google+
3 Replies


RedSon
Expert 5K+
P: 5,000
I think it is a problem with your printf statement. I'm not sure what though since you have edited your output to be different then what I expect the code to output. Also, why did you decide to make some of your variables double precision and others float?
Jan 31 '07 #2

P: 64
I think it is a problem with your printf statement. I'm not sure what though since you have edited your output to be different then what I expect the code to output. Also, why did you decide to make some of your variables double precision and others float?

Well, to tell you the truth I wasn't sure why it was working so I just played around with the lf, d, c, and even some other things. Here is the exact question the book asks me to do and maybe you can give me a small code so I can get idea how it works.

1. prompt the user to enter a number (type double).
2. read number (using %lf).
3. Generate a random number and scale it to range 2...8.
4. Set result to number divided by the random number.

Ex.One output could be
number: 127.50 <<-- user input
the random number 2
result 63.75 <<-- 127.50 / 2 = 63.75
Jan 31 '07 #3

P: 64
Thanks again guys! But I was able to figure out what I did wrong.
Feb 1 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.