I'm trying to create a map-related calculator and I'm having a problem with the Math.Round method. Basically, I want the program to take the real-life length and the length on a map to calculate the scale of said map. After it calculates the scale it should round it from a double to an int.
So for example the real-life length is 3000000 cm and the on map length equals 8,5 cm now after dividing these we get 352 941,176 that's our scalenoteven in this context. Now after rounding it, the scale should be 1:352 941 but instead the program gives me a scale of 1:352.
double Scalenoteven;
int Scaleeven;
//RealLengthincm and Maplength are taken from the user
Scalenoteven = RealLengthincm / MapLength;
Scaleeven = (int)Math.Round(Scalenoteven, 1, MidpointRounding.ToEven);
So with the added culture info and RealLengthincm = RealLength * 100; this should be working.
using System.Globalization;
double RealLength;
string RealLengthString;
double MapLength;
string MapLengthString;
double RealLengthincm;
double Scalenoteven;
int Scaleeven;
Console.WriteLine("Firstly will the real length be in meters or kilometers?");
string Answer;
Answer = Console.ReadLine();
if (Answer == "meters")
{
Console.WriteLine("Alright!");
Console.WriteLine("So what's the real length?");
var culture = new CultureInfo("de-DE");
RealLengthString = Console.ReadLine(); // assuming 30000
RealLength = double.Parse(RealLengthString, culture);
RealLengthincm = RealLength * 100;
Console.WriteLine("now what's the length on the map in cm");
MapLengthString = Console.ReadLine(); // assuming 8,5
MapLength = double.Parse(MapLengthString, culture);
//RealLengthincm and Maplength are taken from the user
Scalenoteven = RealLengthincm / MapLength;
Scaleeven = (int)Math.Round(Scalenoteven, 0, MidpointRounding.ToZero);
Console.WriteLine("The Scale is 1:" + Scaleeven); // outputs 1:352941
}
Related
I am trying to show the percentage after a number is subtracted.
Example:
Cost of work = £165.00
Workers charge = £42.00
Left Over = %
What is the percentage of Cost left after the worker has got his cut.
My Code output is showing 0
int number = 0, number1, result = 0;
if (Int32.TryParse(SelectedQuoteForEditing.JobPrice, out number) && Int32.TryParse(Rate.Content.ToString().ToString(), out number1))
{result = number - number1;}
JobPercentage.Content = result.ToString();
The simple formula is PART / MAX * 100
In your fault It should look like this:
double costOfWork = 165;
double workersCharge = 42;
double left = Math.Round((costOfWork - workersCharge) / costOfWork * 100, 2);
It calculates the remaining cost using costOfWork - workersCharge.
Then it calculates how many percents the remaining cost is.
It's getting rounded to two digits.
I ran across the issue in C#- FileComparison
double size = (LengthOfTxt-LengthOfDocx) / LengthOfDocx / 100;
I have some problems with my code where I think the accuracy is a bit off. I'll take out the declarations of variables from my code, so the code is as small as possible:
int a = Int32.Parse(tb_weight.Text);
double b = 0;
b = (a * 1.03) / 1000;
double g = 0;
g = (1.09 + (0.41 * (Math.Sqrt(50 / b))));
lbl_vertforce.Content = Math.Round((b * g * 9.81), 2);
So, tb_weight is a textbox where the input is made, and lets say the input is 5000, the label lbl_vertforce is showing 119,61 and according to my calculator, it should show 119,74. What is wroing here?
Doubles are not 100% precise and can vary in the least common digits. If you want exact precision you need to use Decimal type which has a bigger memory foot print, but was designed to be very precise. Unfortunately Math.Sqrt is not overloaded for Decimal and only works on doubles. I have provide code I found in another posting discussing the subject of Decimal Square roots: Performing Math operations on decimal datatype in C#?
public void YourCodeModifiedForDecimal()
{
int a = Int32.Parse(tb_weight.Text);
decimal b = 0;
b = (a* 1.03m) / 1000m;
decimal g = 0;
g = (1.09m + (0.41m * (Sqrt(50m / b))));
lbl_vertforce.Content = Math.Round((b* g * 9.81m), 2);
}
public static decimal Sqrt(decimal x, decimal? guess = null)
{
var ourGuess = guess.GetValueOrDefault(x / 2m);
var result = x / ourGuess;
var average = (ourGuess + result) / 2m;
if (average == ourGuess) // This checks for the maximum precision possible with a decimal.
return average;
else
return Sqrt(x, average);
}
You need to round g to 2 decimal places to get 119.74 in the final calculation.
g = Math.Round(1.09 + (0.41 * (Math.Sqrt(50 / b))), 2);
In my if statement (LengthCalculatorOption == 1), I want to convert, for example, 187.96cm to feet and inches, such as 6feet 2ins. How do I do that? In my current code, it shows 6.17feet and always 0ins. I have no idea why.
static void Main(string[] args) {
double Centimetres = 0.0, Feet = 0.0, Inches = 0.0;
string AnotherConversion = null;
string LengthCalculatorMenu;
int LengthCalculatorOption;
do {
LengthCalculatorMenu = ("Enter 1) Convert centimetres to feet and inches:"
+ "\nEnter 2) Convert feet and inches to centimetres:");
Console.Write(LengthCalculatorMenu);
LengthCalculatorOption = int.Parse(Console.ReadLine());
if (LengthCalculatorOption == 1) {
Console.WriteLine("Please Enter the Centimetres(cm) that you wish to convert to feet and inches");
Centimetres = double.Parse(Console.ReadLine());
Feet = (Centimetres / 2.54) / 12;
Inches = (Centimetres / 2.54) - (Feet * 12);
Centimetres = ((Feet * 12) + Inches) * 2.54;
Console.WriteLine("\nThe equivalent in feet and inches is {0:C} ft {1:G} ins", Feet, Inches);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any other key to exit):");
AnotherConversion = Console.ReadLine();
} else if (LengthCalculatorOption == 2) {
Console.WriteLine("Please Enter the Feet");
Feet = double.Parse(Console.ReadLine());
Console.WriteLine("Please Enter the Inches");
Inches = double.Parse(Console.ReadLine());
Centimetres = ((Feet * 12) + Inches) * 2.54;
Console.WriteLine("\nThe equivalent in centimetres is {0:G}cm", Centimetres);
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any other key to exit):");
AnotherConversion = Console.ReadLine();
} else {
Console.WriteLine("\n\a\t Invalid Option!Option Must be 1 or 2");
}
} while (AnotherConversion == "y" || AnotherConversion == "Y");
Try this:
Feet = (Centimetres / 2.54) / 12;
int iFeet = (int)Feet;
inches = (Feet - (double)iFeet) * 12;
To elaborate a bit:
You are defining feet as a double, which means that it will be a decimal value. So since you're dividing by 12, it can become a decimal representation.
What my code does is it converts Feet to integer (which will round it to 6 in this situation). We then subtract the double version of Feet (6.17 in this situation) which equals .17 (The remainder). We multiply that by 12 to convert from .17 feet to inches
Edit
To expand based on Scott's comment, this would be a different way to go
int totalInches = (Centimetres / 2.54); // This will take a floor function of Centimetres/2.54
int Feet = (totalInches - totalInches % 12) / 12; // This will make it divisible by 12
int inches = totalInches % 12; // This will give you the remainder after you divide by 12
To calculate a value in centimeters into feet and inches, you'd likely want to do this:
double centimeters = 187.96;
double inches = centimeters/2.54;
double feet = Math.Floor(inches / 12);
inches -= (feet*12);
Generally-speaking, one should convert down to the most basic level, then calculate your way up. This way, you only do the work of converting one time, instead of having to repeat the conversion calculation. In this insntance, I do the simple conversion of centimeters to inches, and then after that, count the number of feet in inches, then subtract that much from the final inches value.
So, if I had, say, 38 inches, I would have Math.Floor(38 / 12) feet, or 3. Then inches would be set to 38 - (3*12), which is 2, giving a final result of 3 feet, 2 inches.
Keeping it as double, use:
double inp = 12.75; // e.g.
double feet = Math.Floor(inp);
double inches = (inp - feet) * 12.0;
Try this:
double F = Math.Floor(Centimetres * 0.0328084);
Feet = Centimetres * 0.0328084;
Inches = (Feet - F) * 12;
1 ft = 0.30480m
Some general-purpose methods:
public static class Converter
{
public static (int Feet, double Inches) CentimetresToFeetInches(double centimetres)
{
var feet = centimetres / 2.54 / 12;
var iFeet = (int)feet;
var inches = (feet - iFeet) * 12;
return (iFeet, inches);
}
public static string CentimetresToFeetInchesString(double centimetres, string footSymbol = " foot", string inchesSymbol = " inches")
{
(var feet, var inches) = CentimetresToFeetInches(centimetres);
return $"{feet:N0}{footSymbol}, {inches:N0}{inchesSymbol}";
}
}
Usage:
(var feet, var inches) = Converter.CentimetresToFeetInches(178);
//feet == 5
//inches == 10.078740157480315
var feetInchesString = Converter.CentimetresToFeetInchesString(178);
//5 foot, 10 inches
I am having trouble with my bmi calculator.
Here are the details:
Write a program that takes a person's height and
weight in pounds and returns the body mass index(BMI).
BMI is defined as the weight, expressed in kilograms, *divided by the square of the height expressed in meters.*
One inch is 0.0254 meters and one pound is
0.454 kilograms.
This is a windows form app btw.
Well when I am trying to square the height using ^, it gives me an error: Operator '^'...
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
//Declare variables.
decimal heightDecimal ;
decimal weightDecimal;
decimal bmiDecimal;
decimal resultDecimal;
//Get user input.
heightDecimal = Decimal.Parse(txtHeight.Text);
weightDecimal = Decimal.Parse(txtWeight.Text);
//Calculations.
weightDecimal = (Decimal)0.454;
heightDecimal = (Decimal)0.0254;
bmiDecimal = weightDecimal / heightDecimal ^ 2;
//Display.
lblBMI.Text = bmiDecimal.ToString();
}
I am trying to figure out the calculations. I am confused. Can anyone please help me? Thanks.
Tested what everyone said. I got some weird numbers. I started it and I put 5 for my height and 100 for my weight(random) and I got 700? Are my calculations wrong?
bmiDecimal = weightDecimal / heightDecimal ^ 2;
You probably meant
bmiDecimal = weightDecimal / (heightDecimal * heightDecimal);
^ is the XOR operator in C#.
Edit:
If you don't use metric unit, you have to multiply the results by 703.06957964, see Wikipedia.
bmiDecimal = weightDecimal / (heightDecimal * heightDecimal);
Try the above. ^ is xor
Alternatively
bmiDecimal = weightDecimal / Math.Pow(heightDecimal, 2)
Some test values could be 90 kg and 1.80 m
90 / (1.80 * 1.80)
90 kg is roughly 200 lbs and 1.80 m is 5.11 if you're not used to the metric system
Here's what it would look like in a Console App:
decimal feetDecimal;
decimal inchesDecimal;
decimal weightDecimal;
decimal bmiDecimal;
decimal resultDecimal;
//Get user input.
Console.WriteLine("Enter feet:");
feetDecimal = Decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter inches:");
inchesDecimal = Decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter weight in pounds:");
weightDecimal = Decimal.Parse(Console.ReadLine());
//Calculations.
inchesDecimal += feetDecimal * 12;
decimal height = inchesDecimal * (decimal)0.0254;
decimal weight = weightDecimal * (decimal)0.453592;
bmiDecimal = weight / (height * height);
//Display.
Console.WriteLine(bmiDecimal.ToString());
Console.ReadLine();
The .NET Framework also provides a Math class that has a Pow method, which allows for squaring of numbers like this:
Math.Pow(2, 2)
That is 2 squared, which equals 4.
Your code would be:
bmiDecimal = weightDecimal / Math.Pow(heightDecimal, 2);
Note: For more information read documentation for Math.Pow.
Weight = Convert.ToDecimal(txtWeight.Text);
Height = Convert.ToDecimal(txtHeight.Text);
BodyMassIndex = (Weight * 703) / (Height * Height);
txtMassIndex.Text = Convert.ToString(Math.Round(BodyMassIndex, 4) + " lbs/ Inch Square");
I need to split an double value, into two int value, one before the decimal point and one after. The int after the decimal point should have two digits.
Example:
10.50 = 10 and 50
10.45 = 10 and 45
10.5 = 10 and 50
This is how you could do it:
string s = inputValue.ToString("0.00", CultureInfo.InvariantCulture);
string[] parts = s.Split('.');
int i1 = int.Parse(parts[0]);
int i2 = int.Parse(parts[1]);
Manipulating strings can be slow. Try using the following:
double number;
long intPart = (long) number;
double fractionalPart = number - intPart;
What programming language you want to use to do this? Most of the language should have a Modulo operator. C++ example:
double num = 10.5;
int remainder = num % 1
"10.50".Split('.').Select(int.Parse);
/// <summary>
/// Get the integral and floating point portions of a Double
/// as separate integer values, where the floating point value is
/// raised to the specified power of ten, given by 'places'.
/// </summary>
public static void Split(Double value, Int32 places, out Int32 left, out Int32 right)
{
left = (Int32)Math.Truncate(value);
right = (Int32)((value - left) * Math.Pow(10, places));
}
public static void Split(Double value, out Int32 left, out Int32 right)
{
Split(value, 1, out left, out right);
}
Usage:
Int32 left, right;
Split(10.50, out left, out right);
// left == 10
// right == 5
Split(10.50, 2, out left, out right);
// left == 10
// right == 50
Split(10.50, 5, out left, out right);
// left == 10
// right == 50000
how about?
var n = 1004.522
var a = Math.Floor(n);
var b = n - a;
Another variation that doesn't involve string manipulation:
static void Main(string[] args)
{
decimal number = 10123.51m;
int whole = (int)number;
decimal precision = (number - whole) * 100;
Console.WriteLine(number);
Console.WriteLine(whole);
Console.WriteLine("{0} and {1}",whole,(int) precision);
Console.Read();
}
Make sure they're decimals or you get the usual strange float/double behaviour.
you can split with string and then convert into int ...
string s = input.ToString();
string[] parts = s.Split('.');
This function will take time in decimal and converts back into base 60 .
public string Time_In_Absolute(double time)
{
time = Math.Round(time, 2);
string[] timeparts = time.ToString().Split('.');
timeparts[1] = "." + timeparts[1];
double Minutes = double.Parse(timeparts[1]);
Minutes = Math.Round(Minutes, 2);
Minutes = Minutes * (double)60;
return string.Format("{0:00}:{1:00}",timeparts[0],Minutes);
//return Hours.ToString() + ":" + Math.Round(Minutes,0).ToString();
}
Try:
string s = "10.5";
string[] s1 = s.Split(new char[] { "." });
string first = s1[0];
string second = s1[1];
You can do it without going through strings. Example:
foreach (double x in new double[]{10.45, 10.50, 10.999, -10.323, -10.326, 10}){
int i = (int)Math.Truncate(x);
int f = (int)Math.Round(100*Math.Abs(x-i));
if (f==100){ f=0; i+=(x<0)?-1:1; }
Console.WriteLine("("+i+", "+f+")");
}
Output:
(10, 45)
(10, 50)
(11, 0)
(-10, 32)
(-10, 33)
(10, 0)
Won't work for a number like -0.123, though. Then again, I'm not sure how it would fit your representation.
I actually just had to answer this in the real world and while #David Samuel's answer did part of it here is the resulting code I used. As said before Strings are way too much overhead. I had to do this calculation across pixel values in a video and was still able to maintain 30fps on a moderate computer.
double number = 4140 / 640; //result is 6.46875 for example
int intPart = (int)number; //just convert to int, loose the dec.
int fractionalPart = (int)((position - intPart) * 1000); //rounding was not needed.
//this procedure will create two variables used to extract [iii*].[iii]* from iii*.iii*
This was used to solve x,y from pixel count in 640 X 480 video feed.
Console.Write("Enter the amount of money: ");
double value = double.Parse(Console.ReadLine());
int wholeDigits = (int) value;
double fractionalDigits = (value - wholeDigits) * 100;
fractionalDigits = (int) fractionalDigits;
Console.WriteLine(
"The number of the shekels is {0}, and the number of the agurot is {1}",
wholeDigits, fractionalDigits);
Using Linq. Just clarification of #Denis answer.
var parts = "10.50".Split('.').Select(int.Parse);
int i1 = parts.ElementAt(0);
int i2 = parts.ElementAt(1);