user2086751
user2086751

Reputation:

Trouble generating random numbers?

rndmBid=rand() % (sellPtr->sellPrice + (1.25*sellPtr->startPrice));

whats wrong with this line? Everything is an integer except 1.25 (obviously) and the compiler gives an error which says invalid operands of types 'int' and 'double' to binary 'operator%'.

I tried changing startPrice and rndmBid to double, without luck. Any suggestions?

Upvotes: 1

Views: 84

Answers (4)

David G
David G

Reputation: 96845

The rhs is returning a double, while % only works on integers. Cast the result into an integer:

rand() % static_cast<int>(sellPtr->sellPrice + (1.25 * sellPtr->startPrice));

Upvotes: 2

Sebastian
Sebastian

Reputation: 7720

(sellPtr->sellPrice + (1.25*sellPtr->startPrice) is a double because the result of (1.25*sellPtr->startPrice) is a double because 1.25 is a double. Cast the result to int and it will compile:

rndmBid=rand() % static_cast<int>(sellPtr->sellPrice + (1.25*sellPtr->startPrice));

Upvotes: 2

Chris Chambers
Chris Chambers

Reputation: 1365

You are adding an int to a double, so the result is a double, which cannot be used with the % operator.

To fix this, you need to do:

rndmBid=rand() % ((int)(sellPtr->sellPrice + (1.25*sellPtr->startPrice)));

This will work as long as the double is not bigger than what can fit in an integer.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477580

Once you introduce a double into an arithmetic expression, everything gets promoted/converted to double. So you need to convert back to integer:

rndmBid = rand() % static_cast<int>( ... );

(I trust you realize that your random numbers won't be uniformly distributed.)

Upvotes: 4

Related Questions