3

I have the following code:

int a = Int32.Parse(weight.Text);
double b = 0;

if (this.wcf.SelectedItem == weighing)
{
    b = (a * 1.03) / 1000;
    wll.Content = b.ToString();
}

weight is the name of a TextBox and in this TextBox where the input is made which is 50000. wll is a Label where the calculation of b is shown. wll shows 51.5 which is correct.

I want to use the value of b in a calculation further down and therefore I have defined a new int:

int p = Convert.ToInt32(b);
double g = 0;          

double sq = Math.Sqrt(50 / p);

The value of sq should then be 0,985 and is shown in the label daf, but the program shows 1,492. Something is not correct here, can anyone help me?

g = (1.09 + (0.41 * sq));
daf.Content = g.ToString();
Ian
  • 30,182
  • 19
  • 69
  • 107
  • Be careful with integer divisions. You should use doubles IE 50.0 not 50 – Steve Jan 28 '16 at 11:45
  • I've tried Math.Sqrt(50.0 / p) and I got the same result. – Thomas Eikje Gjerde Jan 28 '16 at 11:54
  • @Ian I will try to investigate and see if I can find any mistakes. But the conversion of the value in the label to an int is done correctly? – Thomas Eikje Gjerde Jan 28 '16 at 11:59
  • @ThomasEikjeGjerde if your `weight.Text` is of the form `50000` or `5000` or `111111`. Then it is ok. ;) but let say it is of the form `12.131`, or `156.41`, or `50.1213`, then it is *not* ok. Basically, you need to find parser which suits with your `string` format. ;) – Ian Jan 28 '16 at 12:01

3 Answers3

1

Beware of this:

int p = Convert.ToInt32(b);
double g = 0;          
double sq = Math.Sqrt(50 / p); //int/int

this will make you have Math.Sqrt(int), losing precision. Instead, you should do:

double sq = Math.Sqrt(50D / p); //double/int

or

double sq = Math.Sqrt((double)50 / p); //double/int

or

double sq = Math.Sqrt(50.0 / p); //double/int

Declare 50 as double

In addition, since your b can have result of non-integer, you may want to change this line too:

int p = Convert.ToInt32(b); //same issue losing precision

into

double p = Convert.ToDouble(b); //use double instead
Ian
  • 30,182
  • 19
  • 69
  • 107
0

One of the main thing that i can see is that in your code you have used

int p = Convert.ToInt32(b);

this will make p = 51 and not 51.1

your code should work fine if you make p as double, and convert to double

double p = Convert.ToDouble(b)
abhinav
  • 31
  • 4
0

First, you are converting b into an int. so you're losing the 0.5 precision, becoming 51, not 51.5. Change your p into a double and don't convert b! that will give you sq as 0,985. Then you are printing out g, not sq. that's why the program is showing 1,492, not 0,985:

daf.Content = sq.ToString();
Balah
  • 2,530
  • 2
  • 16
  • 24