Nistor Alexandru
Nistor Alexandru

Reputation: 5393

Cast int variable to double

I am a beginner C# programmer, and I am trying to create a calculator. I can't seem to figure out how to cast an int variable to a double. This is what I have so far:

public void oImpartire() {
    if (rezultat % value == 0)
    {
        rezultat /= value;
    }
    else {
       (double)rezultat /= value;  // this should be double but I get an error
    }
}

How can I make this work?

EDIT: Both result and value are int variables.

Upvotes: 22

Views: 149163

Answers (5)

user586399
user586399

Reputation:

Try this:

double rezultat = 1992;
rezultat /= value;

resultat must be a double to store the result of rezultat / value. Otherwise, if both resultat and value are int, you won't get floating point numbers. For example, 5 / 3 = 1, but (double)5 / 3 = 1.666667. Notice that the value 1.6666667 is just a double.

Upvotes: 0

MikeD
MikeD

Reputation: 21

If both of your variables are not doubles, assign them into a double variable and then divide.

VarDouble = (double)int.....; VarDouble /= VarDouble1 etc

(double)rezultat /= value

I presume you are trying to make rezultat a double and I presume it's not declared as one and you just can't do that. Your resulting variable that will hold the result must also be a double or you will just get a whole number not rounded.

Upvotes: 2

svick
svick

Reputation: 244757

This depends on the type of the rezultat variable. If it's double, then you don't have to do anything, integer division won't be used in any case. But if it's int, then your cast doesn't make any sense, you can't store a double value in an int variable.

So, the correct solution depends on what exactly do you want to do. But if your goal is to have the result of the actual division as a double, you will need some double variable for that. And if you have that, your if won't make any sense anymore, just use double division in all cases.

Upvotes: 0

user529758
user529758

Reputation:

(double)rezultat /= ...

is not good. The result of a casting expression is always an rvalue, i. e. something that cannot be assigned to. Related: you can't change the type of an expression (you can cast it, but that won't really change its type, just act as another type temporarily). Once you declared your variable as, say, an int, you won't be able to store a double in it - however you cast the division, etc. it will always be truncated in the end.

You most likely have to introduce a double temporary variable to store the result of the division.

Upvotes: 14

Related Questions