# More C questions

Hi, I’m writing a program that will generate a price of a flight(chosen by the user) and I want it to be a random number between 1300 and 1700. at the moment it looks like this:(this is only the price function)
float price(void)
{
cost=rand()%1700+1;
return(cost);
}
I have defined cost as a float previously. At the moment, it generates a number from 1 to 1700, not 1300 to 1700. How do I define a range for a rand() function? thanks

You could just use
cost=rand()%400 +1301;

Hmm, what does the % do? Isn’t that modulo?

cost=rand()*400 +1300;

That’ll work too.

rand() in C is integer, so just multiplying by 400 will not work…
to get an integer price use: 1300 + rand()%401
to get a float price use: 1300 + rand()*(400.0/RAND_MAX)

Note that rand() probably produces the same sequence on each program run, since it is a pseudo-random number.

Hi
If you want it to be a properly random number, seed rand with time (don’t forget to include time.h). I think it goes something like this: rand(seed(time)), but all my c and C++ texts are packed away as we’re moving soon.

good luck.
DT

yes thank you. I had a seedrnd() function defined. I now have another question, I’m doing a switch-case loop. I want a case’10’: but since i’m using char verse; verse=getchar(); switch(verse), it will only accept the ‘1’ from ‘10’ and display what is supposed to go with one. Is there a way to make it accept multiple digits?

i think it would be better if you catch the options with scanf("%d",&variable); so you can do this:

switch(variable){
case 1:{what_you_want();
break;}

`````` case 200:{
what_you_want();
break;}
``````

}//end of switch

That should fix your problem, the thing with getchar(); is that yor manage your value as a character maximum 2 of lenght. 99 for example would be the max value. If you will have values for your “multiple choice” between -32768 and 32767 a simply int variable might work.

if you want to use that integer as a character you must use the function itoa(); within stdlib.h library… That function converts a integer to a string: you may use it this way: