Division in c# not going the way I expect

2019-06-27 07:07发布

问题:

Im trying to write something to get my images to show correctly. I have 2 numbers "breedtePlaatje" and "hoogtePlaatje". When i load those 2 vars with the values i get back "800" and "500" i expect "verH" to be (500 / 800) = 0,625. Tho the value of verH = 0..

This is the code:

int breedtePlaatje = Convert.ToInt32(imagefield.Width);
int hoogtePlaatje = Convert.ToInt32(imagefield.Height);

//Uitgaan van breedte plaatje
if (breedtePlaatje > hoogtePlaatje)
{
    double verH = (hoogtePlaatje/breedtePlaatje);
    int vHeight = Convert.ToInt32(verH * 239);

    mOptsMedium.Height = vHeight;
    mOptsMedium.Width = 239;

    //Hij wordt te klein en je krijgt randen te zien, dus plaatje zelf instellen
    if (hoogtePlaatje < 179)
    {
        mOptsMedium.Height = 179;
        mOptsMedium.Width = 239;
    }
}

Any tips regarding my approach would be lovely aswell.

回答1:

Dividing int by int gives an int.

double verH = (hoogtePlaatje/breedtePlaatje);

The right hand side of the assignment is an integer value.

Change breedtePlaatje and/or hoogtePlaatje to double and you will get the answer you expect.



回答2:

Integer division will result in an Integer being returned as the division result.

You need one of the parameters of the division to be a float in order for the result to be a float. You can do this by casting one of them to a float.

double verH = (double)hoogtePlaatje/breedtePlaatje;

Or

double verH = hoogtePlaatje/(double)breedtePlaatje;

See the C# spec regarding division.



回答3:

When you divide two integers, C# uses integer division, where the fractional part is discarded. In your case you're getting:

500 / 800 = 0 + 5/8 

Which, discarding the fractional part, gives:

500 / 800 = 0

To get floating point division, cast one of the arguments to either double, float or decimal depending on the level of precision you need, which will cause the other argument to be implicitly converted to the same type and the division carried out using floating point rules instead of integer rules, e.g.

double result = (double)breedtePlaatje  / hoogtePlaatje ;


回答4:

I have never used C#, but probably you will need to cast one of the variables to double, like this:

double verH = (double)hoogtePlaatje/breedtePlaatje;


回答5:

Try this:

double verH = double (hoogtePlaatje) / breedtePlaateje;

If you divide an int by an int, you will get a truncated answer. Cast one of them up to a double, and the entire division will be done as double.



标签: c# double scale