c++ - Loss of accuracy with the return statement in my code -
i'm learning c++ through great tutorial @ http://www.learncpp.com/cpp-tutorial/210-comprehensive-quiz part of quiz need create calculator code seems drop decimal. believe occurs during return statement. anyways, newbie learning c++ appreciated. code:
#include "stdafx.h" #include <iostream> int input(float); int math(double, double, char); void print(double); int _tmain(int argc, _tchar* argv[]) { double fnumberone = input(0); double fnumbertwo = input(1); char operator = input(2); print(math(fnumberone, fnumbertwo, operator)); return 0; } int input(float x) { using namespace std; if (x == 0) { cout << "please enter first number" << endl; double input; cin >> input; return input; } if (x == 1) { cout << "please enter second number" << endl; double input; cin >> input; return input; } if (x == 2) { cout << "please enter operator" << endl; char op; cin >> op; return op; } } int math(double x, double y, char op) { double result(0); if (op == '+') result = x + y; if (op == '-') result = x - y; if (op == '/') result = x / y; if (op == 'x') result = x *y; return result; } void print(double x) { using namespace std; cout << x << endl; }
when return function input
returning int
:
int input(float x) { ... double input; cin >> input; return input; // cast happens here turn double int.
you need return double ie double input(float x)
.
Comments
Post a Comment