Ok, so this is the question I am trying to do,
Write two functions having same name Add and takes two arguments. When
called from main, they will print “I have been called n times” where n is the
number of calls, they have received from main, and will return the sum of
arguments passed.
And the following is the code I made for this program.
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
|
#include <iostream>
using namespace std;
int add(int, int, int &, int &);
double add(double, double, int &, int &);
int main()
{
double a, b, d;
int x = 0, y = 0;
char c;
bool fh = true;
while (fh)
{
cout << "Enter first number: ";
cin >> a;
cout << "Enter second number: ";
cin >> b;
d = add(a, b, x, y);
cout << endl << "Sum = " << d;
cout << endl << "Would you like to add another numbers? " << endl << "Type Y for yes: ";
cin >> c;
cout << endl;
if (c == 'y' || c == 'Y')
fh = true;
else
fh = false;
}
cout << endl;
system("pause");
return 0;
}
int add(int a, int b, int &x, int &y)
{
int c;
x++;
cout << "I have been called " << x << " times" << endl;
c = a + b;
return c;
}
double add(double a, double b, int &x, int &y)
{
y++;
double c;
cout << "I have been called " << y << " times" << endl;
c = a + b;
return c;
}
|
Program runs fine, however, I am getting one big issue here... For what I know, in this program, now if user enters a number without decimal then the program is supposed to take that as integer and take it to the function with integer parameters. But it is not doing that... It is taking it to function with double parameters instead..
To resolve it, I tried to change a and b in main function to integers however, that didn't work and resulted in program running for infinite time.
Is there any possible way to solve it? How can I make the program to take the variables a and b to the parameters to double function only when I enter decimal value in one of these 2 variables? Thank you!
(Just for example, this is the output I am getting right now)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
Enter first number: 2
Enter second number: 3
I have been called 1 times
Sum = 5
Would you like to add another numbers?
Type Y for yes: y
Enter first number: 3
Enter second number: 2
I have been called 2 times
Sum = 5
Would you like to add another numbers?
Type Y for yes: y
Enter first number: 2.13
Enter second number: 4
I have been called 3 times
Sum = 6.13
Would you like to add another numbers?
Type Y for yes:
|