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);
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
}
{
int priceforprimer = 0;
double H, L, W, Finthearea = 0;
priceforprimer = int.Parse(textBox9.Text);
H = double.Parse(textBox5.Text);
L = double.Parse(textBox6.Text);
W = double.Parse(textBox7.Text);
Finthearea = H * L * W;
priceforprimer = Finthearea / 13;
textBox8.Text = Finthearea.ToString();
Hello, my assignment is to work out the area of the wall and then work out how many tins of primer is needed for that wall exactly as "Paint is purchased as full tins of paint only." The double values work and I can calculate the area, but the division doesn't. Per 13m of wall works out as one tin of primer. I have been trying for 2 hours with this, but I am lost, also pretty new to C# which makes it trickier. Thanks.
//These are typical ceiling samples in C#. You also need to adopt naming //conventions in your code (i.e names like textbox5 are not standard)
using System;
class Program
{
static void Main()
{
// Get ceiling of double value.
double value1 = 123.456;
double ceiling1 = Math.Ceiling(value1);
// Get ceiling of decimal value.
decimal value2 = 456.789M;
decimal ceiling2 = Math.Ceiling(value2);
// Get ceiling of negative value.
double value3 = -100.5;
double ceiling3 = Math.Ceiling(value3);
// Write values.
Console.WriteLine(value1);
Console.WriteLine(ceiling1);
Console.WriteLine(value2);
Console.WriteLine(ceiling2);
Console.WriteLine(value3);
Console.WriteLine(ceiling3);
}
}
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 somehow get one number before floating point and value after that floating point. Example:
Before: 212.12345;
After: 2.12345
Any Ideas?
Assuming you have:
decimal x = 212.12345m;
you can use the modulo operator:
decimal result = x % 10;
Note that the number should be represented as a decimal if you care about the accurate value.
See also: Meaning of "%" operation in C# for the numeric type double
You can do like this:
public double GetFirst(double a)
{
double b = a / 10.0;
return (b - (int)b) * 10.0;
}
try this
double x = 1;
var y = x/10;
var z = (y % (Math.Floor(y))) * 10;
Try this code
string num = "15464612.12345";
string t = num.Split('.')[0];
num = t[t.Length-1].ToString() + "." + num.Split('.')[1];
my approach was to find the number 210, and substract it....
will work for any number as well as smaller then 10.
double f1 = 233.1234;
double f2 = f1 - (((int)f1 / 10) * 10);
The result of all of the division equations in the below for loop is 0. How can I get it to give me a decimal e.g.:
297 / 315 = 0.30793650793650793650793650793651
Code:
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100;
long result2 = i / 100;
double result3 = i / 100;
float result4 = i / 100;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})", i, 100, i / 100, result, result2, result3, result4);
}
Console.ReadLine();
}
}
}
Answer:
Thanks Jon and everyone, this is what I wanted to do:
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
int maximum = 300;
for (int i = 0; i <= maximum; i++)
{
float percentage = (i / (float)maximum) * 100f;
Console.WriteLine("on #{0}, {1:#}% finished.", i, percentage);
}
Console.ReadLine();
}
}
}
You're using int/int, which does everything in integer arithmetic even if you're assigning to a decimal/double/float variable.
Force one of the operands to be of the type you want to use for the arithmetic.
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100m;
long result2 = i / 100;
double result3 = i / 100d;
float result4 = i / 100f;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})",
i, 100, i / 100d, result, result2, result3, result4);
}
Results:
0/100=0 (0,0,0, 0)
1/100=0.01 (0.01,0,0.01, 0.01)
2/100=0.02 (0.02,0,0.02, 0.02)
3/100=0.03 (0.03,0,0.03, 0.03)
4/100=0.04 (0.04,0,0.04, 0.04)
5/100=0.05 (0.05,0,0.05, 0.05)
(etc)
Note that that isn't showing the exact value represented by the float or the double - you can't represent 0.01 exactly as a float or double, for example. The string formatting is effectively rounding the result. See my article on .NET floating binary point for more information as well as a class which will let you see the exact value of a double.
I haven't bothered using 100L for result2 because the result would always be the same.
Try
i / 100.0
because i is an int: i / 100 performs integer division, then the result, that is always 0, is casted to the target type. You need to specify at least one non-int literal in your expression:
i / 100.0
Because i is an integer and 100 is an integer...so you have an integer division
Try (decimal)i / 100.0 instead
No matter where you store it, an integer divided by an integer will always be an integer.
You need to force a floating point operation "double / double" instead of an "int / int"
double result = (double)297 / (double)315 ;
this is integer division whatever the type of variable you storing in,
so int / int = int
double result3 = ((double)i) / 100;
Because i is a int value and you divide by an integer so the result is an integer ! and so you need to divide by 100.0 to have an implicit cast in float or specify 100f or 100d
In my case I had only vars and no int
float div = (var1 - var2) / float.Parse(var1.ToString());