0

I've inserted a variable of type Double in the application/settings file and I'm using a "while" loop to do a small calculation:

double final=0;
double cost = application.settings.default.cost; // 0.15
while(true) 
{
    Thread.Sleep(1000); //speeded up version of 60000 (1 minute)
    final+=cost;
    //code that waits for the user to quit the loop
}

the result after 1 hour should be 9.00 but it's calculating to something like 24.00 :/ however, if I hardcode the value in to the code, I get the desired result of 9.00

double final=0;
double cost = 0.15
while(true) 
{
    Thread.Sleep(1000); //speeded up version of 60000 (1 minute)
    final+=cost;
    //code that waits for the user to quit the loop
}

Any ideas?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
user2864613
  • 169
  • 1
  • 4
  • 10

1 Answers1

3

Thread.Sleep(1000); does not mean that your code is executed exactly every second. If you run your code this way 10 times for 1 hour you will get 10 different results.

This was discussed here as well: How accurate is Thread.Sleep(TimeSpan)?

(although there Thread.Sleep is used with a TimeSpan. The main issue stays the same)

Edit:

I don't know what exactly your are calculating. But calculating costs in this way is not a good approach as it is very inaccurate.

Better take a timestamp when you start calculating your costs and take another one when you are finished. Take the difference of both timestamps and you can calculate the costs quite accurately. Your method gets more and more inacurrate the longer your code us running.

Community
  • 1
  • 1
user1567896
  • 2,398
  • 2
  • 26
  • 43
  • 2
    The difference in result is too big 9/0.15 are 60 iterations, 24/0.15 are 160 iterations, even accounting for milliseconds of difference in thread sleep, something different is at work here – Steve Oct 19 '13 at 15:53
  • Still no luck here.. guess I will hard code it for now. Not sure why someone downvoted.. perhaps they would like to provide some help instead? :) – user2864613 Oct 19 '13 at 16:22