mardi 5 février 2019

C++: IF/ELSE comparisons with positive & negative values

I have a CLR project that I am building. The program operates as follows:

Step1: User inputs survey heading, then clicks Calculate.

Step2: User inputs observed headings and enters them into text fields

Step3: User clicks buttons to calculate the difference between calculated headings and observed headings

Step4: Difference in headings are put in new text fields

Ok, so basically we have a compass that is calibrated and we observe headings on a secondary compass relative to the first. The difference between those 2 headings is our final output.

I'm trying to write up an If/Else statement that will evaluate the difference and write the number in a specific color based on whether or not it passes the criteria of a 0.5 tolerance.

Currently I'm using:

varOut1 = (DiffCalc1 - ObsHdgDbl);
        if (varOut1 < .5) {
            this->Diff1->Font = (gcnew System::Drawing::Font(L"Arial", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->Diff1->ForeColor = System::Drawing::Color::SpringGreen;
        }
        else {
            this->Diff1->Font = (gcnew System::Drawing::Font(L"Arial", 9, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
                static_cast<System::Byte>(0)));
            this->Diff1->ForeColor = System::Drawing::Color::Red;
        }
        Diff1Final = (varOut1.ToString("n2"));
        Diff1->Text = Diff1Final;

So far, this works to an extent... but the problem is that sometimes the Difference is a negative number.

Example: CalculatedHdg = 40.45, ObservedHdg=40.52, Diff1=.07 In this example, the code works because it is within the described statement so the output is in green.

If you have ObservedHdg=41.52 then the output is printed in red... However if you have ObservedHdg=31.52 then output is still in green even though the overall difference is above .5. The difference can be a Positive or Negative number based on the observed value, so I need a statement that will evaluate if Diff1 is within the tolerance of .5 whether positive or negative.

I'm a little rusty on my If/Else comparisons for math evaluations. I've attempted searches on advanced If/Else comparisons but mostly I come across examples explaining how to use the && vs || vs <=, etc.

Any help would be greatly appreciated. Thanks.

Aucun commentaire:

Enregistrer un commentaire