+ 2

How do I make both my integer and double functions add its numbers?

I just wrote a brand new code based on two functions: ints and doubles. However, whenever I compile the program, I can't get the changes that I want from both functions. The first function is supposed to add 1 to both 3's included for x and y while the second function adds 1.5 to both a and b. #include <iostream> using namespace std; int myFunction(int &a); double myFunctions(double &b); int main() { int x = 3; int y = 3; double a = 4.0; double b = 4.0; cout << x << " and " << y << " are the chosen numbers." << endl << endl; cout << "The numbers above share the same first function: " << endl; myFunction(x); myFunction(y); cout << "\nx is now: " << x; cout << "\ny is now: " << y << endl << endl; cout << a << " and " << b << " are the new chosen numbers." << endl << endl; cout << "The new numbers above share the same second function: " << endl; myFunctions(a); myFunctions(b); cout << "\na is now: " << a; cout << "\nb is now: " << b << endl; } int myFunction(int &a) { int new_a = a + 1; return (new_a); } double myFunctions(double &b) { double new_b = b + 1.5; return (new_b); } And one more question, can a function be used to convert an int into a double or a double to int? And an int or a double share the exact same function?

11th Sep 2018, 3:06 AM
Andy Cruz
Andy Cruz - avatar
2 Respuestas
+ 2
I assume you are using Reference by parameter concept in C++ If that's the case: In myFunction() you have declared new_a variable and has value a + 1(new_a= a + 1) so now new_a has value 4(3+1) not int a To modify value of variable a the expression in myFunction should be a = a+1(a+=1) Similar case for double b variable. Also you don't need to return values from myFunction and you can use same function name(myFunction) for both functions but with different parameters(int and double) I have used your code and done some modifications please have look: https://code.sololearn.com/ct943N8vIky9/?ref=app
11th Sep 2018, 4:04 AM
Digambar Bhujabal
Digambar Bhujabal - avatar
+ 1
You're unintentionally mixing different passing mechanisms. Use one only. The difference is explained in the course: https://www.sololearn.com/learn/CPlusPlus/1643/ // Pass by value. Use assignment x = foo(x) to change x. int foo(int a) { return a + 1; } // Pass by reference. Just call foo(x) to modify x void foo(int& b) { b += 1; } int can be converted to double (widening) and vice versa (narrowing), without the need of any function. (due to the range of int falls completely in the range of double). double a = 3; // Widening is safe. // Narrowing isn't, the decimal part is truncated. int a = 3.4; // And the compiler will generate a warning. // Cast 3.4 to int, there will be no warning, but 0.4 is still truncated. int a = static_cast<int> (3.4); If you're expecting double arithmetic on an int, cast it to double.
11th Sep 2018, 5:41 AM
Hoàng Nguyễn Văn
Hoàng Nguyễn Văn - avatar