-5

I got this homework today. A worker works for an amount of days (inputted by the user). 5% of the days he gets a bonus money (the amount is also inputted by the user). The length of workday is measured in hours. The number of workhours must be different and random for every day.For example day1 the workhours are 8 day2-4 day3-12 etc.

All the user input things are done, but when it comes to the calculations part I've made this loop.

for (int i=0;i<= totalDays;i++)
  {
    daysWithBonus=totalDays*(5/100)
    bonusIncome=daysWithBonus*Bonus
    moneyForTimeWorked=timeWorked*paymentForHour
    totalIncome=bonusIncome+moneyForTimeWorked
  }


Now my problem is that I can not get the timeWorked variable to be random and different for every day.I found this in the web:


int timeWorked = rand() % 9 + 3;
but it does not seem to work. Every time I run the program I get 8 for the value of the variable for each day. Can someone help me figure this out?

Alex Johnson
  • 958
  • 8
  • 23
D.Dimitrov
  • 13
  • 1
  • 2

2 Answers2

1

Because rand is pseudorandom. It is the same for every run so you can do better debugging for example. Take a look at srand, and use the time of your pc as a seed. That is: add srand(time(0)); to your code.

Edit: Reference this question.

kkica
  • 4,034
  • 1
  • 20
  • 40
0

It's important to understand that rand() is "pseudorandom." Give it a proper seed value (like the current time) via srand() and then it should give you random values, like so:

/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}

From here: http://www.cplusplus.com/reference/cstdlib/srand/

I think using rand() in the context of simple schoolwork is fine. And as was previously pointed out, you need to be careful when calling rand() repeatedly (like in a loop) as this may give you duplicate numbers.

Alex Johnson
  • 958
  • 8
  • 23