static_cast<float> for division of int

Simple calculator. How to get the static_cast to change from int to float?

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
#include <iostream>
using namespace std;

int Calculate(int x, int y, char chOperation)
	{	
		switch(chOperation)
		{
		case '/': 
			return  x = (x % y != 0) ? 
			(static_cast<float>(x) / y) : (x / y);
		case '*': 
			return x * y;
		case '+': 
			return x + y;
		case '-': 
			return x - y;
	
		default:	
			cout << "Error." << endl;
			break;
		}
	}
 

int main()
{
while(1)

	{
	cout << "\n--------------------------------\n" << endl;
	int x, y; char chOperation;
	cout << "Calculator: ";
	cin >> x;
	cin >> chOperation;
	cin >> y;

	cout << "\n--------------------------------\n" 
	<< x << " " << chOperation<< " "
	<< y << " = " << Calculate(x, y, chOperation);
	}
	
	return 0;
}
firstly i'd cast the denomitor.
secondly that wont work in the current state as your function returns an int.
You'd have to make it return a float.
firstly i'd cast the denomitor.
secondly that wont work in the current state as your function returns an int.
You'd have to make it return a float.


So, if I were to just give it a return ternary instead of "x =" ? Need a little more clarification. Below doesn't work either.

1
2
3
return (x % y != 0) ? 
(x / static_cast<float>(y)) : 
(x / y);
Last edited on
Your function itself returns int. int Calculate(. No matter what you return, it will be casted to int, because this is what you told it to do.
I see, thanks MiiNiPaa.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
float Calculate(float x, int y, char chOperation)
{
	
	switch(chOperation)
	{
	case '/': 
		return x / y; 
	case '*': 
		return x * y;
	case '+': 
		return x + y;
	case '-': 
		return x - y;
	
	default:	
		cout << "Error." << endl;
		break;
	}
}

This works.

I had to change both: float Calculate(float x ... into a float. If it was just "Calculate" or "x" it would not work.
Topic archived. No new replies allowed.