PDA

View Full Version : What's wrong with my C# code?


xFear of Napalm
06-12-2010, 12:30 AM
I'm sorry if I'm missing something dead
basic, but I'm extremely new to C#, and
basically all programming in general. I'm
trying to build some basic things on my
own to practice Syntax and get a better
feel for the language. I'm currently using
Visual C# Express 2010, and I'm writing a
simple-as-hell program to covert Celsius
temperatures to Fahrenheit, and vise versa.

For some reason, when I enter a temperature
in the Fahrenheit textBox, "fText", and try
to convert it, it will always equal zero in the
Celsius textBox, cText. My integers for the
temperatures are f and c. Could this alone
cause this problem?

Here is my code for my Fahrenheit to Celsius
button, the only one I've completed. Is there
anything visibly wrong?

private void fcButton_Click(object sender, EventArgs e)
{
int f;
int c;
f = int.Parse(fText.Text);
c = ((5 / 9) * (f - 32));
cText.Text = Convert.ToString(c);
}

Should the variables be declared elsewhere?
Does the last line not work like I think it should?
What's a good alternative to this, and why?

Thanks for helping, and just remember, I'm as
new to this as humanly possible, and internet-
taught. Also, I'm sorry for taking this much room
to post my problem, I just wanted to be descriptive.

CrzySdrs
06-12-2010, 12:49 AM
It's been a while since I have written C#, but if it's like C it's interpreting your 5/9 as integer operations (which would result in a zero), when you want to do floating point math. I suspect the fix would be as simple as changing those to floating point numbers and you will see results more along the lines you are expecting.


private void fcButton_Click(object sender, EventArgs e)
{
int f;
int c;
f = int.Parse(fText.Text);
c = ((5.0 / 9.0) * (f - 32));
cText.Text = Convert.ToString(c);
}

oracleguy
06-12-2010, 12:50 AM
c = ((5 / 9) * (f - 32));

This is the problem, 5 / 9 equals 0 in the context of integers. So you have 0 * (f -32) which will obviously always be zero.

c should be a double instead of an integer. And then the fraction should be (5.0 / 9.0) that tells the compiler that you want a floating point number instead of an integer.

Does that make sense?

Looks like CrzySdrs beat me to it, his code is basically the same except this line:
c = ((5.0 / 9.0) * (f - 32)); would need to be this if you keep c as an integer:
c = Convert.ToInt32(((5.0 / 9.0) * (f - 32)));

xFear of Napalm
06-12-2010, 12:54 AM
Thank you both for replying - I didn't even know that would make a difference, but I guess I barely understand any of the syntax of the language, but I chose the integer because I thought I would need the extra range in values, because disk space isn't a concern with me. Thanks, though, it's pretty useful to know (: