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.");
  • 2
    Integer division problem: `3 / 2 = 1`, but `3.0 / 2 = 1.5`; turn at least one value into `double` e.g. `double antalGaster = (double)dagskassa / lunchpris;` – Dmitry Bychenko May 29 '20 at 17:21
  • 1
    For why the _truncating_, in details: https://stackoverflow.com/q/10851273/2864740 , https://stackoverflow.com/q/1043164/2864740 , https://stackoverflow.com/q/3498421/2864740 - if the goal is to "round up" (or _whatever it might be_), add that to search queries "C# integer division round up", etc. – user2864740 May 29 '20 at 17:24
  • `int lunchpris = int.Parse(inlasning2); //from inlasning -> inlasning2` `double antalGaster = (double)dagskassa / lunchpris;` – Manish Dalal May 29 '20 at 22:56

2 Answers2

3

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
Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

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);
Georges
  • 11
  • 3
  • Whoops! just edited to account for that, thanks Rufus – Georges May 29 '20 at 22:54
  • Also, `System.Math.Floor` will create a truncated integer, not _rounding_ to the nearest integer (as in `System.Math.Round`). Be careful what language you use about rounding. Consider using `Round` instead of `Floor`, or else update your text to say it will truncate instead of round. – Sean Skelly May 29 '20 at 23:25
  • Yes, I’ve chosen floor here as any increment above a whole number would represent a fraction of a person. I think System.Math.Round would be more appropriate for an example not related to a count of how many people you can accommodate – Georges May 29 '20 at 23:52