Question

subtracting negative numbers in c++

Asked by: Aiysha

How do I subtract two negative numbers in c++. I have declared them as double

double txtlong;
double Flong;
 
txtlong= -91.9472
Flong= -91.92250
 
double longdistance;
longdistance=Flong-txtlong;  <----- this line does not give the correct answer.

                                  
1:
2:
3:
4:
5:
6:
7:
8:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-03-30 at 09:50:35ID24277956
Topics

Programming Languages

,

C++ Programming Language

Participating Experts
7
Points
500
Comments
25

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Excel-- negative numbers and subtracting
    I'm not sure what the formula is to subtract the values of 2 or more cells. Also, How are negative numbers processed? I have a cell which adds two cells and divides by another. If the number happens to be negative, then the value in the answer cell is in parenthases. Is t...
  2. Subtracting Negative Numbers Issue
    I've posted my code below, it's a practice problem from the book I'm working in. I can't seem to figure out how to get negative numbers to show up. I converted all of my module variables to Double but that didn't fix my problem. I've been going over this for upwards of an hou...
  3. need to subtract sysdates and not get negatives
    Here is the deal. Originally I set up 2 timestamp columns in the format of 12 instead of military time of 24 (now I have it in the format of 12). So, when I go to subtract column timestamp from column B timestamp, i sometimes get negative numbers. I do not want the negat...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mrjoltcolaPosted on 2009-03-30 at 10:01:19ID: 24020810

What do you think the correct answer is?

What is a negative number minus a negative number?

 

by: InteractiveMindPosted on 2009-03-30 at 10:02:36ID: 24020823

You forgot some semicolons

#include <iostream>
 
using namespace std;
 
int main()
{
    double txtlong;
    double Flong;
 
    txtlong= -91.9472;
    Flong= -91.92250;
 
    double longdistance;
    longdistance=Flong-txtlong;
 
    cout << longdistance << endl;
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:

Select allOpen in new window

 

by: AiyshaPosted on 2009-03-30 at 10:06:41ID: 24020858

the correct answer is  0.0247
and i am getting  -2.46999

The program is doing
91.92250-91.9472 = -2.46999

 

by: AiyshaPosted on 2009-03-30 at 10:07:32ID: 24020866

The program is doing
91.92250-91.9472 = -2.46999
instead of
The program is doing
-91.92250-(-91.9472) = -2.46999

 

by: itsmeandnobodyelsePosted on 2009-03-30 at 10:11:45ID: 24020906

If you want the absolute difference of the numbers do

   longdistance=abs(Flong-txtlong);  


I wonder why these variables have so odd names?

 

by: AiyshaPosted on 2009-03-30 at 10:14:43ID: 24020933

I am working with geological data..its subtracting the longitude of fields and finding the distance from sources.

 

by: AiyshaPosted on 2009-03-30 at 10:15:30ID: 24020938

itsmeandnobodyelse,
subtracting the mod is a good idea, but how I preserve the sign of the greater number?

 

by: itsmeandnobodyelsePosted on 2009-03-30 at 10:24:24ID: 24021035

>>>> The program is doing
>>>> 91.92250-91.9472 = -2.46999

Why should the compiler do such strange things?

Why should it convert negative input values to positive ones and why should it return negative result where a positive result is correct?

 

by: AiyshaPosted on 2009-03-30 at 10:27:37ID: 24021071

I was hoping you experts can help me figure this out.

 

by: mrjoltcolaPosted on 2009-03-30 at 10:29:07ID: 24021086

I don't get the wrong answer. Verify your code, perhaps?

My code below outputs:

0.03
0.03
0.03
-0.03

#include <iostream>
#include <cmath>
 
using namespace std;
 
int main()
{
    double txtlong;
    double Flong;
 
    Flong= -91.92;
    txtlong= -91.95;
 
    double longdistance;
    //           -91.92 +91.95
    longdistance= Flong - txtlong;
 
    cout << longdistance << endl;
    cout << std::abs(Flong - txtlong) << endl;
    cout << Flong - txtlong << endl;
    cout << txtlong - Flong << endl;
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

Select allOpen in new window

 

by: AiyshaPosted on 2009-03-30 at 10:34:08ID: 24021143

does this have any influence on the calculation

#include "stdafx.h"

#include <iostream.h>
#include <math.h>             instead of <cmath>

I am creating a .dll in c++ to be called from vb 6.0

 

by: itsmeandnobodyelsePosted on 2009-03-30 at 10:37:38ID: 24021174

>>>> but how I preserve the sign of the greater number?

Hmmm. Normally you would operate with either positive numbers or either negative numbers. Building the difference of a positive and a negative coordinate doesn't make so much sense, or?

But you can make you a helper sign function like

int signOfDbl(double d)
{
       return (d < 0.)?  -1 : 1;
}

Then

        signOfDbl(FLong);

would return 1 if FLong is positive or 0.0 and -1 else.

If you know that both numbers (must) have the same sign, you could have

   int sgn =  signOfDbl(FLong);

and have the sign of both.

if the numbers can have different signs the bigger number always has positive sign. If you need the sign of the number which is absolute bigger than the other you can do

   double x = 3.1;
   double y  = -5.7;

   int sgn = signOfDbl(x - y);  // == sign of y




 

 

by: mrjoltcolaPosted on 2009-03-30 at 10:39:23ID: 24021185

No, it should not affect builtin C++ mathematic operations on a double.

Since your original sample was not legal C++ I am suspicious as to your actual code and would prefer to see the real code.

 

by: itsmeandnobodyelsePosted on 2009-03-30 at 10:42:53ID: 24021214

>>>> does this have any influence on the calculation

No. Though you normally wouldn't use precompiled headers (stdafx.h) for a dll.

>>>> I was hoping you experts can help me figure this out.

How did you get the result of -2.46999 ?

The code you posted didn't compile because of the missing semicolons?

The code mrjoltcola posted - same as my own test code - see below - have the correct results? Could you show how you come to the wrong results?

int main()
{
   double txtlong;
   double Flong;
    
   txtlong= -91.9472;
   Flong= -91.92250;
    
   double longdistance;
   longdistance=Flong-txtlong;
 
// here I set a breakpoint
   return 0;
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: AiyshaPosted on 2009-03-30 at 10:58:04ID: 24021376

Following is my c++ and vb 6.0 code
 
// example1.cpp : Defines the entry point for the DLL application.
//
 
#include "stdafx.h"
#include <iostream.h>
#include <math.h>
 
BOOL APIENTRY DllMain( HANDLE hModule, 
                       DWORD  ul_reason_for_call, 
                       LPVOID lpReserved
					 )
{
    return TRUE;
}
 
 
 
double _stdcall sum(double x , double y, double m, double n, double i)
 
{
 
 
double latdistance;
double longdistance;
double txtlong;
double txtlat;
double Flong;
double Flat;
double comparelong;
double comparelat;
double N_S_distance;
double E_W_distance;
double iValue;
double rValue;
	
Flat=x;
txtlong= n;
Flong = y;
txtlat=m;
iValue=i;
 
 
latdistance=Flat-txtlat;
longdistance=Flong-txtlong;
 
 
if (longdistance < 0.00) 
{comparelong=-1.00;}
if (longdistance>0.00)
{comparelong=1.00;}
 
 
if (latdistance<0.00)
{comparelat=-1.00;}
if (latdistance>0.00)
{comparelat=1.00;}
 
 
 
N_S_distance=comparelong*acos(cos(((90-txtlat)*3.14159265)/180)*cos(((90-txtlat)*3.14159265)/180)+sin(((90-txtlat)*3.14159265)/180)*sin(((90-txtlat)*3.14159265)/180)*cos(((txtlong-Flong)*3.14159265)/180))*3440.65;
E_W_distance=comparelat*acos(cos(((90-txtlat)*3.14159265)/180)*cos(((90-Flat)*3.14159265)/180)+sin(((90-txtlat)*3.14159265)/180)*sin(((90-Flat)*3.14159265)/180)*cos(((Flong-Flong)*3.14159265)/180))*3440.65;
 
 
if (iValue==1.0) 
{ rValue=latdistance;}
if(iValue==2.0)
{rValue=longdistance;}
if(iValue==3.0)
{rValue=N_S_distance;}
if(iValue==4.0)
{rValue=E_W_distance;}
 
 
 
return rValue;
 
}
 
-----------------------------------------------------------------------------------------------
 
Private Declare Function sum Lib "example1.dll" (ByVal x As Double, ByVal y As Double, ByVal m As Double, ByVal n As Double, ByVal p As Double) As Double
Private Sub Command1_Click()
Dim x, y, m, n, q
 
x = CDbl("29.890280")
m = CDbl("-91.92250")
y = CDbl("-91.9472")
n = CDbl("28.0")
q = CDbl("2.0")
 
 
Text3.Text = sum(x, y, m, n, q)
End Sub
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:

Select allOpen in new window

 

by: VenabiliPosted on 2009-03-30 at 11:03:16ID: 24021429

Just a note here: make also sure that you are not printing the number in the E form
0.0247 = 2.47E-2 which with can be printed as 2.46999 if you are not careful what you print. It still does not explain the sign change though.
As the posted code is obviously not the used one, this is also probably part of the problem

 

by: mrjoltcolaPosted on 2009-03-30 at 11:08:09ID: 24021485

Aiysha: Your question has now evolved to a VB / C++ interop question. We answered your original question, and I just want to say I have nothing else to comment on regarding your VB / DLL stuff, so as not to be rude and seem like I am ignoring further comments, I am stepping out. I imagine the error is not in the plain C++. You might consider posting a new question cross-zone to Microsoft C++ and VB forums.

Or maybe itsmeandnobodyelse will see your error. Good luck! I'll check back later.

 

by: itsmeandnobodyelsePosted on 2009-03-30 at 11:30:34ID: 24021717

>>>> Flat=x;
>>>> txtlong= n;
>>>> Flong = y;
>>>> txtlat=m;
>>>> iValue=i;
 
 
>>>> latdistance=Flat-txtlat;
>>>> longdistance=Flong-txtlong;

That means:
 
latdistance= x - m  = 29.890280 - (-91.92250) = 121,81278;
longdistance= y - n = -91.9472 - 28.0 = -119,9472;

It seems to me that you were not subtracting the same qualities (and in your question you have a difference of   -91.92250 - -91.9472 but not in the real code !!!).

But goon:

As you were passing last argument 2.0 the following should apply

if(iValue==2.0)
{rValue=longdistance;}

Hence the return value should be
 
-119,9472;


>>>> if(iValue==2.0)

It is dangerous to compare two double values for equality cause the same double may have different internal binary representation what could make the condition false, i. e. the 2.0 may be 1.9999999999999999999 at one platform and 2.000000000000000 at the other both printing  2.0 as output. You better would pass the iValue as integer where you don't have such risks.

 

by: AiyshaPosted on 2009-03-30 at 12:30:15ID: 24022366

itsmeandnobodyelse:

Thank you soo much for pointing out the problem. I took your advice and passed iValue as int, but vb gives me error as the function sum() cannot find its entry point.

After correcting the input values I still get
-91.9472- -91.92250 = 2.46999
instead of
-91.9472- -91.92250 = 0.024720
Do you think the compiler has problem outputting numbers less than 1?..silly question but forgive me I am very new to C++.

 

by: AiyshaPosted on 2009-03-30 at 12:31:18ID: 24022373

mrjoltcola:
Thank you very much for your response. I completely understand and I am very grateful for the help you provided.

 

by: KimpanPosted on 2009-03-30 at 14:07:15ID: 24023361

Put a break point in your VB code and see if CDbl is converting correctly. The decimal separator in the string is dependant of the locale settings in your system.

You should also declare the variables with explicit types
Dim x, y, m, n, q as Double

 

by: HooKooDooKuPosted on 2009-03-30 at 15:04:25ID: 24023930

Changing iValue to an int is a bit of a red-herring.
Whole numbers that are 15 digits or less are represented by doubles exactly.  So when you say something like "X = 2.0", it will be stored as exactly 2.0.  It's when you say something like "X = 2.1" that the number might actually get stored as "2.0999999999999999" or something.  But since iValue is being set to a whole number and being compared to a whole number, itsmeandnobodyelse point, while correct, isn't the issue for THIS situation.

Additionally, the reason you can't find the entry point is that you can't just simply change the declaration of a function defined in a DLL.  In other words, the DLL currently has a function 'sum', and when you delcare that function for use by VB, the VB declare MUST match what is in the DLL.  So the only way you can change iValue to an integer is if you change it in both the VB AND C DLL code to be an integer.  And then you would have to make sure they are BOTH 16 bit integers (in VB, Integer is a 16 bit integer, in C, int can be a 16 or 32 bit integer depending upon the compiler).

To ensure the DLL function is getting called correctly, you must follow Kimpan's advice and declare all your VB variables as Double.  Otherwise, they by default get declared as a variant, and you are then attempting to pass a variant to a library the want a double.  And I'm not sure that VB is properly doing that for you.

So at this point, you need to change iValue back to a double, and specifically declare all your VB variables as doubles (i.e., since "sum" takes 5 doubles, you need to pass 5 doubles rather than 5 variants).

Now where itsmeandnobodyelse will be correct, the code...
x = CDbl("29.890280")
m = CDbl("-91.92250")
y = CDbl("-91.9472")
will NOT set these values to exactly the values shown.  From the point of view of a floating point number they will be basically the same, but you might find that "y" actually is "91.94719999999" or something like that.

If possible, the C code should be changed to initialize rValue = 0.  That way, if I'm wrong and itmeandnobodyelse's comments are causing the problem, what whould be happening is that what ever random data located at rValue is getting returned (because the if statements wouldn't be moving anything into rValue, and what ever code recently executed would have set data where rValue is located, so you could be getting the same random number over and over).

 

by: itsmeandnobodyelsePosted on 2009-03-30 at 15:05:09ID: 24023940

>>>> but vb gives me error as the function sum() cannot find its entry point.

You would need to change both signatures, in C++ and VB, to have the last argument an integer.

>>>> After correcting the input values I still get
>>>> -91.9472- -91.92250 = 2.46999
Please forgive me, if I have still doubts that the input values you expect to have passed are the ones which were used for calculation.

The -91.9472 was passed as m and the -91.92250 was passed as y. As you have pairs of same quality (x, y) and (m, n), there is at least a flaw in naming if not more. Be also aware that the output of 2.46999 might be a 2.46999E-2 f not using the appropriate output formats.

>>>> Do you think the compiler has problem outputting numbers less than 1?..

I do C++ for more than 16 years. All these times I have found two or three real compiler bugs and maybe 5 or six flaws in the runtime libraries and MFC. All other cillion of errors were errors I made myself. Hence you actually must not look for a compiler bugs but simply make sure that the numbers you pass were not mixed up. BTW, if you would name the arguments similar to that they were meaning, it would simplify the issue by grades.  

 

by: aegis007Posted on 2009-03-31 at 14:29:46ID: 24033881

Hi,

If you need add a negative sign to the variable longdistance.

Hope it solves your problem.

Regards,
AeGIs007.

long txtlong;
long Flong;
 
txtlong= -91.9472
Flong= -91.92250
 
long longdistance;
 
longdistance= (labs(Flong)-labs(txtlong)); 

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:

Select allOpen in new window

 

by: AiyshaPosted on 2009-04-01 at 09:36:23ID: 31564415

itsmeandnobodyelse and venabili helped me out, but I dont know how to split the points.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...