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);
Related
i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.
The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler
You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
Let's say I have the following code:
int digit1 = 1;
int digit2 = 3;
and I need to combine the two integers, resulting in a floating-point number equal, in this case, to 13.0f. This is probably easy, as I'm new to C# and learning it from a book, but how is it done?
Example:
int digit1 = 3;
int digit2 = 6;
float result = combine_integers (digit1, digit2);
// result = 36
NOTE:
I don't actually need a function. I just did that for the sake of the example.
float combine_integers (int digit1, int digit2)
{
return 10*digit1 + digit2;
}
Example
combine_integers(1, 3) ==>
10 * 1 + 3 ==>
10 + 3 ==>
13
combine_integers(3, 6) ==>
10 * 3 + 6 ==>
30 + 6 ==>
36
If your integers are single digits, then abelenky's answer above is going to do it quickest for you. If they're not single digits, then you could do string.Format() as above, but there's also a couple of edge cases that aren't covered, such as negative values or both values being 0.
The string operations above could produce results such as "00", "5-1", or throw an error for not being able to parse the string result. In the case of {5,-1}, you could end up with 49.
What I would do is cover my bases and assume that if you use a negative number, you want the absolute value. This code also covers the base case of single digits, but gives you some flexibility so that combine_integers(12,34) returns 1234.0f.
static float combine_integers (int digit1, int digit2)
{
int checker = Math.Abs(digit2);
int result = Math.Abs(digit1);
do
{
result *= 10;
checker /= 10;
} while(checker>0);
result += Math.Abs(digit2);
return (float)result;
}
private static float combine_integers(int a, int b)
{
return float.Parse(a.ToString() + b.ToString());
}
https://dotnetfiddle.net/M9Bpwt
Try this code:
int digit1 = 3;
int digit2 = 6;
string concat = string.Format("{0}{1}", digit1, digit2);
float result = float.Parse(concat);
I am receiving an error "Operator '*' cannot be applied to operands of type 'int' and 'decimal[]'", as I am attempting to multiply two values with different data types (one being a value located in an array). My question is how am I able to multiple numberOfMinutes * perMinuteRate in my code below? My variable is called total, which I declared a double data type (although may be incorrect).
I tried changing data types and played with formatting (like ToString), but I am not sure what to do. I also tried to google the answer with no success.
I am by no means a professional programmer; I'm not in school. I'm a data analyst who is learning to program.
Here is my code:
static void Main(string[] args)
{
int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
decimal[] perMinuteRate = { .07m, .1m, .05m, .16m, .24m, .14m };
int numberOfMinutes;
int userAreaCode;
string inputString = "1";
while (inputString != "0")
{
int x;
Console.WriteLine("Enter the area code for your call (or 1 to end):");
inputString = Console.ReadLine();
userAreaCode = Convert.ToInt32(inputString);
Console.WriteLine("How many minutes will your call last?");
inputString = Console.ReadLine();
numberOfMinutes = Convert.ToInt32(inputString);
for (x = 0; x < areaCodes.Length; x++)
{
if (userAreaCode == areaCodes[x])
{
***double total = numberOfMinutes * perMinuteRate;***
Console.WriteLine("You call to {0} will cost {1} per minute for a total of {2}.", areaCodes[x], perMinuteRate[x].ToString("C"), total.ToString("C"));
x = areaCodes.Length;
}
}
if (x != areaCodes.Length)
{
Console.WriteLine("I'm sorry; we don't cover that area.");
inputString = "1";
}
else
{
Console.WriteLine("Thanks for being our customer.");
inputString = "0";
}
Console.ReadLine();
}
}
Thank you in advance.
Change:
double total = numberOfMinutes * perMinuteRate;
to
double total = (double)(numberOfMinutes * perMinuteRate[x]);
The same way you index into perMinuteRate in the line directly below.
The expression [int] * [decimal] will result in a decimal, and the cast (double) will convert it to a double
To avoid loss of precision, change it to:
decimal total = numberOfMinutes * perMinuteRate[x];
private void txtFinal_Leave_1(object sender, EventArgs e)
{
int prelim;
int midterm;
int final;
decimal average;
string remarks;
prelim = int.Parse(txtPrelim.Text);
midterm = int.Parse(txtMidterm.Text);
final = int.Parse(txtFinal.Text);
average = (prelim + midterm + final) / 3;
txtAverage.Text = average.ToString();
if (average >= 75)
{
remarks = "passed";
}
else
{
remarks = "failed";
}
txtRemarks.Text = remarks;
// this is the output 83 passed
// I want to be like this 83.25 passed
}
average = (prelim + midterm + final) / 3.0m;
This will fix your problem.
Int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.
You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.: 3.0m this is casting to decimal !
please upgrade your code as follow:
average = Convert.ToDecimal(prelim + midterm + final) / 3;
txtAverage.Text = string.Format("{0:0.00}", average);
All began with these simple lines of code:
string s = "16.9";
double d = Convert.ToDouble(s);
d*=100;
The result should be 1690.0, but it's not. d is equal to 1689.9999999999998.
All I want to do is to round a double to value with 2 digit after decimal separator.
Here is my function.
private double RoundFloat(double Value)
{
float sign = (Value < 0) ? -0.01f : 0.01f;
if (Math.Abs(Value) < 0.00001) Value = 0;
string SVal = Value.ToString();
string DecimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
int i = SVal.IndexOf(DecimalSeparator);
if (i > 0)
{
int SRnd;
try
{
// вземи втората цифра след десетичния разделител
SRnd = Convert.ToInt32(SVal.Substring(i + 3, 1));
}
catch
{
SRnd = 0;
}
if (SVal.Length > i + 3)
SVal = SVal.Substring(0, i + 3);
//SVal += "00001";
try
{
double result = (SRnd >= 5) ? Convert.ToDouble(SVal) + sign : Convert.ToDouble(SVal);
//result = Math.Round(result, 2);
return result;
}
catch
{
return 0;
}
}
else
{
return Value;
}
But again the same problem, converting from string to double is not working as I want.
A workaround to this problem is to concatenate "00001" to the string and then use the Math.Round function (commented in the example above).
This double value multiplied to 100 (as integer) is send to a device (cash register) and this values must be correct.
I am using VS2005 + .NET CF 2.0
Is there another more "elegant" solution, I am not happy with this one.
Doubles can't exactly represent 16.9. I suggest you convert it to decimal instead:
string s = "16.9";
decimal m = Decimal.Parse(s) * 100;
double d = (double)m;
You might just want to keep using the decimal instead of the double, since you say you'll be using it for monetary purposes. Remember that decimal is intended to exactly represent decimal numbers that fit in its precision, while double will only exactly represent binary numbers that do.
Math.Round(number, 1)
Edit I got the wrong question - the rounding problems are inherent to a floating point type (float, double). You should use decimal for this.
The best solution for not going be crazy is:
string s = "16.9";
For ,/.
double d = Convert.ToDouble(s.Replace(',','.'),System.Globalization.CultureInfo.InvariantCulture);
For rounding:
Convert.ToDouble((d).ToString("F2"));