I am trying to convert the ouput of this recursive function to double, but no matter what I try the output remains integer. Could someone please assist.

``````int main()
{
int x,y;
cout << "Please enter the low value of the range to add: " << endl;
cin >> x;
cout << "Please enter the high value of the range to add: " << endl;
cin >> y;
cout << "The sum of the range is: " << static_cast<double>(addRange(x,y)) << endl;
cin.get();//To keep console window open
cin.get();//To keep console window open
return 0;
}

double addRange(int x, int y)
{
if (x > y)
return (0);
else
return static_cast<double>(addRange(static_cast<double>(x) + 1,y)) + x;
}``````

## All 7 Replies

Why all the horrible casting?
Why not just change the function to take in doubles?

``````double addRange(double x, double y)
{``````

This is an assignment question and we were spcifically asked to return a double from this recursive function that passes two int parameters. It is senseless, I know :-)

>no matter what I try the output remains integer
If you perform an operation on two integers that wouldn't have any precision even if converted to a double, why would you expect anything but a zero precision? No amount of casting will create something that isn't there.

``````#include <iostream>
using namespace std;
double addRange(int x, int y);
int main() {
int x, y;
cout << "Please enter the low value of the range to add: " << endl;
cin >> x;
cout << "Please enter the high value of the range to add: " << endl;
cin >> y;
cout << "The sum of the range is: " << addRange(x, y) << endl;
cin.get();//To keep console window open
cin.get();//To keep console window open
return 0;
}

double addRange(int x, int y) {
if (x > y)
return (0);
else
return (addRange(x + 1, y)) + x;
}``````

lol, works fine...

>lol, works fine...
Yes, but I imagine the OP wants the precision to be printed as well. Input of 1 and 5 should print 15.000000 rather than 15, for example. To do that has nothing to do with the type and everything to do with how it's printed:

``cout<<"The sum of the range is: "<< fixed << addRange(x, y) <<endl;``

Thank you for the help. I agree there is no point to the conversion exercise except to teach me something else I didn't know. This sounds pretty silly to me too.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.