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");
Related
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
}
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 have a excel formula I am trying to "translate" into c# code.
It is used to calculate an "annuity rate" over time (for example 20 years).
=(((1+E26/100)^D28*((1+E26/100)-1))/((1+E26/100)^D28-1))*100
D28 = 20 (years)
E26 = 5,00 (the rate in percent)
the ^ stands for exponent in Excel
As a result with these numbers I expect 8,02% per annum.
I tried several approaches using Math.Pow but wasn't successful.
Here is my first approach which gives me a result of 5 somehow.
double usagePanels = 20.0
double rate = 5.0
annPanels = (Math.Pow((1 + rate / 100), usagePanels) *
((1 + rate / 100) - 1) /
Math.Pow(1+rate/100, (usagePanels-1))) * 100;
Thank you.
Try:
double usagePanels = 20.0
double rate = 5.0
double annPanels = (Math.Pow((1 + rate / 100), usagePanels) *
(rate / 100.0)) /
Math.Pow(1+rate/100, usagePanels)-1)) * 100;
You've got the closing bracket, between usagePanels and the -1, wrong...
(I found this by breaking the formula apart in Excel and in C# and comparing each part.)
EDIT: Another handy tip for comparing Excel to C# is to give the cells in Excel a name (via the Named Range feature) that way the Excel formula can be made to look closer to variable names...
This should do the trick:
double rate = 5;
double years = 20;
double annunity = Math.Pow(1 + rate / 100, years) * (rate / 100) / Math.Pow(1 + rate / 100, years - 1) * 100;
For clarity, the working result is
double usagePanels = 20.0
double rate = 5.0
annPanels = (Math.Pow((1 + rate / 100), usagePanels) *
((1 + rate / 100) - 1) /
(Math.Pow(1+rate/100, (usagePanels))-1)) * 100;
Thanks to Jason Allen and Grhm who basically figured it out and gave great advice.