简体   繁体   中英

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.");

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM