简体   繁体   English

如何除整数而不是 1

[英]How do I divide integers and not get a 1

Just a simple console program in c#.只是 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.答案始终是 1,但我想得到正确的答案,并且答案始终是 integer,这里只有整数。

        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 :这里的问题是您将相同的数字两次转换为两个不同的变量,然后将它们相除,因此答案将始终为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()要四舍五入到人数的最低整数,请使用 Math.Floor()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 你如何划分整数并在C#中获得双倍? - How do you divide integers and get a double in C#? 如何将两个整数相除以获得双精度? - How can I divide two integers to get a double? 当我将两个整数相除时,如何将百分比作为字符串保留到小数点后一位? - How can I get a percentage to 1 decimal place as a string when I divide two integers? 如何在没有较大中间类型的情况下对整数进行乘法和除法运算? - How can I multiply and divide integers without bigger intermediate types? 如何在 C# 中计算整数的除法和模数? - How can I calculate divide and modulo for integers in C#? 如何划分此代码的结果? - How do I divide the result of this code? 除以零错误,我该如何解决这个问题? - Divide by zero error, how do I fix this? 我如何在某个字符值处分割一个字符串,然后得到这个分割的最后一个字? - How do i divide a string at certain char value and than get the last word of this division? 如何进行递归 function 接收数组,找到它的总和以及除以总和的数组中的整数 - How to do a recursion function that receives an array, find the sum of it and the integers in the array that divide the sum 如果我们在c#中除以两个整数,如何总是得到一个整数 - How to always get a whole number if we divide two integers in c#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM