Kodeco Forums

Screencast: Beginning C# Part 4: Operators

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

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.");