Problem with abs() in a program.

Hi all,

I'm using Herb Schildt's C++ Beginners Guide, using this program from Module 1 Mastery:

// Average the absolute values of 5 numbers.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int i;
double avg, val;
avg = 0.0;
for(i=0; i<5; i++) {
cout << "Enter a value: ";
cin >> val;
avg = avg + abs(val);
}
avg = avg / 5;
cout << "Average of absolute values: " << avg;
return 0;
}

The line in bold is giving me an error in the Dev++ compiler:

In function `int main()':
call of overloaded `abs(double&)' is ambiguous
candidates are: int abs(int)
long long int __gnu_cxx::abs(long long int)
long int std::abs(long int)

The program above is copied directly from the book - is there an error in the program?

Many thanks...
abs accepts either an int, or a long int.

http://www.cplusplus.com/reference/clibrary/cstdlib/abs/

You are trying to give it a double. That double can be cast into an int, or a long int. Both options are viable, so it is ambiguous; which one do you mean? Do you want to cast it to an int, or a long int? Yes, there is an error in the program.

Herb Schildt has a terrible reputation.

http://ma.rtij.nl/acllc-c++.FAQ.html#q6.4 and lots more if you search.

Dev-C++ has a terrible reputation.

http://www.cplusplus.com/forum/articles/36896/
Last edited on
Hi could you just add #include <cmath> and check if it is working or not ?
Blimey, well I never. To be honest, Moschops, I'm only about 60 pages into this book and I've spotted several errors, or what I think are errors.

For example, he has a table that shows this:
int -2,147,483,648 to 2,147,483,647
unsigned int -2,147,483,648 to 2,147,483,647
signed int 0 to 4,294,967,295
short int -32,768 to 32,767
unsigned short int -32,768 to 32,767
signed short int 0 to 65,535

and I'm sure the figures for unsigned int and signed int, and unsigned short int and signed short int are the wrong way around.

So Dev-C++ hasn't been updated in 6 yrs - perhaps I'll look at one of the alternatives.

Thanks for your response Moschops, much appreciated.
Having said all that, I added #include <cmath> as suggested by acpaluri, and it has worked!

Cheers acpaluri, much appreciated :)
The abs in cmath will be similarly ambiguous. In this case, he's getting abs from cstdlib.
Last edited on
Hmmm...you'll obviously know a lot more than me, I'm a total novice - but it's working without any errors after adding that header in...

I'm confused - maybe Herb's confused me ;-)
My mistake; there is an abs in cmath that accepts double - the page http://www.cplusplus.com/reference/clibrary/cmath/ lists it on the left, but not in the tables in the middle, and I missed it.

Herb explains very clearly and in an easy to follow way things that are unfortunately wrong.
Last edited on
Delete } on 14 row.
Topic archived. No new replies allowed.