Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
using abs () to find difference but cann't .....

What I have tried:

C++
#include <iostream>

#include<cmath>
#include<limits.h>
#include<stdio.h>
#include<algorithm>
#include<stdlib.h>


using namespace std;

int main()
{

    long int n=0;
    long int a[n];
    long int value;
    cin>>n;
    for(int i=0; i<n;>    {
        cin>>a[i];
    }
    cin>>value;
    cout<<endl;
    int temp=0,temp2=0;
    float diff=0.0,diff2=0.0;
    for(int i=0; i<n;>    {
        temp=a[i];

        for(int j=i+1; j<n;>        {
            if(i==0)
            {
                if(temp+a[j]==value)
                {
                    temp2=a[j];
                    diff=temp2-temp;
                         diff=abs(diff);
                    cout<<"temp="<<temp<<"temp2="<<temp2<<"diff="<<diff<<endl;
                }
            }


            else
            {
                if(temp+a[j]==value)
                {
                    temp2=a[j];
                    diff2=temp2-temp;
                    diff2=abs(diff2);


                    if(diff2<diff)>
                        diff=diff2;


                    cout<<"temp="<<temp<<"temp2="<<temp2<<"diff="<<diff<<endl;
                }
            }

        }
    }
    cout<<"diff="<<diff<<" value="<<value<<endl;
    int aa=(value+diff)/2;
    int b=(value-diff)/2;
    cout<<"Peter should buy books whose prices are "<<b<<" and "<<aa<<endl;</stdlib.h></algorithm></stdio.h></limits.h></cmath></iostream>
Posted
Updated 14-Mar-16 20:28pm
v2
Comments
Patrice T 15-Mar-16 1:44am    
Define "not working"

#include <stdlib.h>


Abs is defined in the stdlib.h file you can find that out by simply looking at the help for Abs.

If you find you need the float version it is called fabs and is defined in math.h
 
Share this answer
 
v3
Comments
Arthur V. Ratz 21-Mar-16 3:18am    
Good solution. +5
I think you should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]
 
Share this answer
 

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