YassJazzBoiii
YassJazzBoiii

Reputation: 9

How do I divide integers and not get a 1

Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.

        Console.Write("Ange dagskassa (kr): ");
        string inlasning = Console.ReadLine();
        int dagskassa = int.Parse(inlasning);

        Console.Write("Ange nuvarande lunchpris (kr): ");
        string inlasning2 = Console.ReadLine();
        int lunchpris = int.Parse(inlasning);

        double antalGaster = dagskassa / lunchpris;

        Console.WriteLine("Antal gäster: " + antalGaster + "st.");

Upvotes: 1

Views: 397

Answers (2)

Georges
Georges

Reputation: 11

You'll need to cast your ints to double in order for the above to work. For example,

int i = 1;
int j = 2;
double _int = i / j; // without casting, your result will be of type (int) and is rounded
double _double = (double) i / j; // with casting, you'll get the expected result

In the case of your code, this would be

double antalGaster = (double) dagskassa / lunchpris;

To round to the lowest whole number for a head count, use Math.Floor()

double antalGaster = Math.Floor((double) dagskassa / lunchpris);

Upvotes: 0

Rufus L
Rufus L

Reputation: 37020

The problem here is that you're converting the same number twice, to two different variables, and then dividing them, so the answer will always be 1:

int dagskassa = int.Parse(inlasning);
int lunchpris = int.Parse(inlasning);  // You're parsing the same input as before

To resolve this, convert the second input for the lunch price:

int dagskassa = int.Parse(inlasning2);  // Parse the *new* input instead

Upvotes: 3

Related Questions