How to divide integers and get value with decimal part?

8

I'm trying to divide the following values into C #:

Double media = 0.0;
int soma = 7;
int cont = 2;
media = soma / cont;

You are returning 3 .

    
asked by anonymous 10.07.2017 / 15:51

3 answers

13

This has to do with typing. You are dividing 2 integers, so you get an integer, if you want a result that is not integer you need to divide numbers that are not integers, you can do a cast , it's safe to do something that increases precision: / p>

using static System.Console;

public class Program {
    public static void Main() {
        int soma = 7;
        int cont = 2;
        double media = (double)soma / (double)cont;
        WriteLine(media);
    }
}

See running on .NET Fiddle . And no Coding Ground . Also I put it in GitHub for future reference .

You do not need to convert the two operands, if one of them is double , the result will already be double to ensure that it has no loss of precision.

    
10.07.2017 / 15:54
4

It does not make sense for you to use type int which will always return integer.

You can use type decimal or double depending on what you are going to do:

decimal media = 0 , soma = 7 , cont = 2;
media = soma / cont; //retorna 3.5

Here is another simpler and easier way:

double soma = 7;
double cont = 2;
var media = soma / cont; //retorna 3.5

Or you can use Convert.ToDouble() or Convert.ToDecimal() .

Double media = 0;
int soma = 7;
int cont = 2;
media = Convert.ToDouble(soma) / cont; // retorna 3.5
    
10.07.2017 / 17:25
1
public class Program {
        public static void Main() {
            double soma = 7;
            double cont = 2;
            double media = soma / cont;
            WriteLine(media);
        }
    }
    
10.07.2017 / 15:59