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)
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.

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.

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:

case 1:{what_you_want();

 case 200:{

}//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:
itoa (integer_variable,char_variable,radix)

Radix is for the base of the string: 10 for decimal, 16 to hexadecimal, and 2 for binary…

I hope this helps you!!!

And if you want to catch the values within a char variable, i recommend you to convert it to integer to do the “switch” with atoi(char_variable); within stdlib.h too…

thank you. I had tried this before but I used scanf("%s",&verse); instead of scanf("%d",&verse); also, I had case ‘4’: instead of case 4: which is nececary for an int. I had no need to do an atoi or itoa function, it works fine with just scanf’ing an int then switch-case’ing that int. thank you!

i’m glad i can help… and yeap %s is for strings and %d for integers, there a lot more of %'s to work with different types of variables, and the ’ ’ always are used for chars, so when you gonna work with an integer you only have to threat it like a number, not like a character…

A friend of mine owns
I’m sure you could find something there to help you out in the future.