Click here to Skip to main content
15,893,722 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
recently I have downloaded Visual Studio 10 Express C++,
registered it and started using it.
I have made simple windows form app,
with one button and two textBox controls for showing result.
On button click event, program should runt trough a simple
for..next loop and measure the time of execution.
Results are shown in textBox1 and textBox2 controls.

An important part of program code :

private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e)
{
Stopwatch clock;

clock.Start();

int i = 0;
double k = 0;
for (i=0; i<100; i=i+1)
{
k = k + 0.1;
}

clock.Stop();

textBox1->Text = (clock.Elapsed.TotalSeconds).ToString();

textBox2->Text = k.ToString();
}

The problem is that result of successive incrementing of value
of variable k inside looop is incorrect :

k = 9,99999999999998 instead k = 10.

Is this because the version of Visual Studio 10 is EXPRESS
and intended for evaluation only.

What I have tried:

I have read manual for C++, to see if I have made this program code wrong logically, and perhaps because of that error it gives wrong result, and I have found no error inside the code.
Posted
Updated 27-Aug-16 13:46pm
Comments
Richard MacCutchan 28-Aug-16 3:06am    
That is because you are using a floating point variable for your counter. And since you already have the count in i you could just use that instead. It is best to avoid floating point types altogether in normal development, they are only ever needed in complex mathematics.
Perić Željko 28-Aug-16 3:16am    
Thanks, I have changed type of variable k to decimal and it vorks fine.

1 solution

Quote:
The problem is that result of successive incrementing of value
of variable k inside looop is incorrect :

k = 9,99999999999998 instead k = 10.
It is not incorrect.
0.1 is coded in binary floating point value, and you have to know that 0.1 coded in floating point value is not exact. This is the standard coding for c, C++ and C#.
To handle such values with exact coding, you have to specialized library.

One solution id to multiply everything by 10 and use integer and then divide by 10 when you want to display.

Floating point - Wikipedia, the free encyclopedia[^]
C/FloatingPoint[^]
 
Share this answer
 
v2
Comments
Perić Željko 28-Aug-16 3:15am    
It seems that I am going to use variable type of Decimal to partially solve my problem.

https://msdn.microsoft.com/en-us/library/system.decimal%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396&cs-save-lang=1&cs-lang=cpp#code-snippet-1

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900