In this episode, you'll learn about some of the common C# operators and how to use them.
This is a companion discussion topic for the original entry at https://www.raywenderlich.com/3247-beginning-c/lessons/5
In this episode, you'll learn about some of the common C# operators and how to use them.
Hi and thank you so much for this site.
Iāve encountered an issue where I canāt declare a data type after having created the variable. I think I probably donno wtf I am doing.
public float Balance = 88.90f;
public float Tip;
void OnDisable()
{
Tip = (Balance * .15);
}
I get this error:
Cannot implicitly convert type ādoubleā to āfloatā.
I can fix it with:
{
Tip = (float) (Balance * .15);
}
But this is a cast isnāt it, and they should be avoided? Is there a way to declare the variable directly, after the fact?
I can also fix it by declaring both variables as doubles but I still feel like thereās an opportunity to understand whatās going on here. Thanks for any response
Every decimal number in C# is inferred to be a double, unless you tell C# otherwise. In your case, you are doing this:
(Balance * .15);
Balance is a float, but .15 is an inferred double. You need to indicate that .15 is a float. You do this with the small f.
(Balance * .15f);
Now you are multiplying two floats. Forgetting the small f is a common error. Itās one of those āhidden in plain sightā errors.
I hope that helps!
I think I had tried the small f, but I tried it outside the parentheses lol. I thought I wanted the whole expression, Tip, to be a float, since itās Tip that I couldnāt declare initially. Looks like I need to pay attention to the data types of more than just variables
Thanks again!
Hi Ray,
Iām not sure if I understood the challenge right, but werenāt we supposed to calculate the tip we should give? Because when e.g. I enter 100 Dollars balance (thatās the amount my dinner did cost right?) in your script and then 5 tip I get 500 Dollars. Maybe Iām getting it wrong but thatās the way I understood it and coded it:
public float balance;
public float tip;
void OnDisable ()
{
float toPay = 0;
toPay = balance * tip / 100;
Debug.Log ("I have to pay " + toPay + " Dollars as a tip.");