private void textBox1_TextChanged(object sender, EventArgs e)
{
int x = 0;
if (Int32.TryParse(textBox1.Text, out x))
{
var y = 1000000;
var answer = x * y;
displayLabel2.Text = answer.ToString();
}
else
{
displayLabel2.Text = "error";
}
}
All of this code works. But I don't know how to use it if a decimal is inputed. Currently it reads numerical values fine and calculates them fine. But I need it to allow decimal points to be inputted.
Ex. if someone inputed 4.7, then I need 4.7 to be multiplied by 1000000.
You need to use a number type that has precision. You can use either floating types (double or float) or the decimal type.
private void textBox1_TextChanged(object sender, EventArgs e)
{
decimal x = 0;
if (decimal.TryParse(textBox1.Text, out x))
{
var y = 1000000.0M;
var answer = x * y;
displayLabel2.Text = answer.ToString();
}
else
{
displayLabel2.Text = "error";
}
}
You could use decimal instead of int:
decimal x = 0;
if (decimal.TryParse(textBox1.Text, out x))
Related
I'm trying to write a very simple program to calculate liquid nicotine strengh. Basically it's (strengh / nicStrengh) * amount. And it always comes out as 0.
private void lblCalculate_Click(object sender, EventArgs e)
{
int strengh = Convert.ToInt32(txtBoxDesiredStrengh.Text);
int nicStrengh = Convert.ToInt32(txtBoxNicStrengh.Text);
int amount = Convert.ToInt32(txtBoxAmount.Text);
int result = strengh / nicStrengh * amount;
string resultStr = result.ToString();
label1.Text = resultStr;
}
When you divide integer to integer the result is integer as well; e.g.
5 / 10 == 0 // not 0.5 - integer division
5.0 / 10.0 == 0.5 // floating point division
In your case strengh < amount that's why strengh / amount == 0. If you want result being int (say 3) put it as
int result = strengh * amount / nicStrengh;
if you want double result (i.e. floating point value, say 3.15) let system know that you want floating point arithmetics:
double result = (double)strengh / nicStrengh * amount;
Try this
private void button1_Click(object sender, EventArgs e)
{
int s = int.Parse(textBox1.Text);
int n = int.Parse(textBox2.Text);
int a = int.Parse(textBox3.Text);
int result = (s / n) * a;
label1.Text = result.ToString();
}
or this if result is with comma
private void button1_Click(object sender, EventArgs e)
{
double s = double.Parse(textBox1.Text);
double n = double.Parse(textBox2.Text);
double a = double.Parse(textBox3.Text);
double result = (s / n) * a;
label1.Text = result.ToString();
}
Getting this error at futureValue = this.CalculateFutureValue(futureValue, monthlyInvestment, monthlyInterestRate, months);and I'm having trouble figuring out how to fix it. When I look up the error online most of the answers say to make the method decimal instead of void so it can have a return type.
But in part of the requirements for the code "rework the CalculateFutureValue method by making it a void function and adding a fourth parameter representing the future value amount to be returned by this method."
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal monthlyInvestment = Convert.ToDecimal(txtMonthlyInvestment.Text);
decimal yearlyInterestRate = Convert.ToDecimal(txtInterestRate.Text);
int years = Convert.ToInt32(txtYears.Text);
int months = years * 12;
decimal monthlyInterestRate = yearlyInterestRate / 12 / 100;
decimal futureValue = 0m;
futureValue = this.CalculateFutureValue(futureValue, monthlyInvestment, monthlyInterestRate, months);
txtFutureValue.Text = futureValue.ToString("c");
txtMonthlyInvestment.Focus();
}
/
private void CalculateFutureValue(decimal futureValue, decimal monthlyInvestment, decimal monthlyInterestRate, int months)
{
for (int i = 0; i < months; i++)
{
futureValue = (futureValue + monthlyInvestment) * (1 + monthlyInterestRate);
}
}
Here is what they mean by the requirement: instead of this
decimal ComputeSomething(decimal x, decimal y) {
return x*x + y*y;
}
...
decimal result = ComputeSomething(10.234M, 20.5M);
do this:
void ComputeSomething(decimal x, decimal y, out res) {
res = x*x + y*y;
}
...
decimal result;
ComputeSomething(10.234M, 20.5M, out result);
Note the out qualifier in front of the additional parameter res. This means that the parameter is "output", i.e. your method must assign it some value before completion.
The assignment to res inside ComputeSomething will become an assignment to variable result.
You need to pass the variable by reference:
private void CalculateFutureValue(ref decimal futureValue, decimal monthlyInvestment, decimal monthlyInterestRate, int months){ ... }
and
this.CalculateFutureValue(ref futureValue, monthlyInvestment, monthlyInterestRate, months);
See this documentation.
If futureValue had not been initialized with a value before passing it to CalculateFutureValue, the out keyword would have needed to be used in place of ref.
This question already has answers here:
How can I convert String to Int?
(31 answers)
Closed 7 years ago.
private void textBox1_TextChanged(object sender, EventArgs e)
{
var x = textBox1.Text;
var y = 1000000;
var answer = x * y;
}
This is my current code. I want to take the user input from textBox1 and multiply it by 1000000 because it needs to convert the user input. But This code doesn't because x technically isn't a numerical value. How would I get this functioning?
This is getting text, not a number:
var x = textBox1.Text;
Since C# is statically typed, you need to explicitly turn it into a number. For this you can use something like int.TryParse(). For example:
var xText = textBox1.Text;
var x = 0;
if (!int.TryParse(xText, out x))
{
// display an error to the user
return;
}
var y = 1000000;
var answer = x * y;
That way you're testing if the text input can be parsed as a number and, if it can't, displaying a message to the user. Rather than assuming the input and getting an unhandled exception.
There are also TryParse() methods for other numeric types, in case you want to use something like a double or a float for other calculations.
You can use Int32.Parse if you're sure user input is a number or int.TryParse if you need to validate it.
I'm assuming integer inputs only what could be wrong though. Same applies for other numeric types. (they all have Parse and TryParse)
Using Int32.Parse
private void textBox1_TextChanged(object sender, EventArgs e)
{
var x = Int32.Parse(textBox1.Text); // you're sure text is numeric
var y = 1000000;
var answer = x * y;
}
Using Int32.TryParse
private void textBox1_TextChanged(object sender, EventArgs e)
{
int x = 0;
if (Int32.TryParse(textBox1.Text, out x)) // you're NOT sure if text is numeric
{
var y = 1000000;
var answer = x * y;
}
else
{
// let the user know that numeric values are required
}
}
This will get you your numerical values
private void textBox1_TextChanged(object sender, EventArgs e)
{
float x = Float.Parse(textBox1.text, CultureInfo.InvariantCulture);
float y = 1000000;
float answer = x * y;
}
I am working on a employee paycheck calculator using several private methods. The methods will determine overtime hours and regular hours. I also must create methods for regular pay and overtime pay. My question is can I feed the results from the hours methods into the methods that will determine pay? If that is possible, how would it work? The method in question is CalculateBasePayAmount--can I pass a result from another method into here?
Here is a look at what I've got so far. Thanks for any help anyone could provide!
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//Determine Hours Method
private decimal DetermineBasePayHours(decimal parhoursWorked)
{
decimal baseHours = 0;
decimal overtimeHours = 0;
if (parhoursWorked <= 40)
{
baseHours = parhoursWorked;
}
else if (parhoursWorked > 40)
{
overtimeHours = parhoursWorked - 40;
baseHours = parhoursWorked - overtimeHours ;
}
return baseHours;
}
private decimal DetermineOverTimeHours(decimal parHoursWorked, string parCategory)
{
decimal overtimeHours = 0;
if (parHoursWorked > 40 && parCategory!="MGR")
{
overtimeHours = parHoursWorked - 40;
}
return overtimeHours;
}
private decimal CalculateBasePayAmount(decimal basePayHours, string parCategory)
{
decimal basePay = 0;
decimal mgrWage = 20;
decimal salesWage = 15;
decimal staffWage = 10;
basePayHours= DetermineBasePayHours(basePayHours);
if(parCategory == "MGR" && basePayHours > 40)
{
basePay = 40 * mgrWage;
}
else
{
basePay = basePayHours * mgrWage;
}
if (parCategory =="SR")
{
basePay = basePayHours * salesWage;
}
else if (parCategory == "STF")
{
basePay = basePayHours * staffWage;
}
return basePay;
}
protected void butCalcPay_Click(object sender, EventArgs e)
{
////1. Declare Variables
//decimal mgrWage = 20;
//decimal salesWage = 15;
//decimal staffWage = 10;
//decimal basePay = 0M;
//decimal salesOvertime = 22.50M;
//decimal staffOvertime = 15;
//decimal overtimeHours = 0;
//decimal overtimePay = 0;
//decimal totalPay = 0;
decimal totalHours = 0;
decimal bpHours;
decimal otHours;
string empCat;
decimal basePay;
//2. Get Values for Variables
totalHours = Convert.ToDecimal(txtNumberHours.Text);
empCat = Convert.ToString(ddlCategory.SelectedValue);
// 3. Methods Called
bpHours = DetermineBasePayHours(totalHours);
otHours = DetermineOverTimeHours(totalHours, empCat);
basePay = CalculateBasePayAmount(totalHours, empCat);
// 4. Display Results
lblbasePay.Text = "Base Pay " + basePay.ToString("C");e here
can I feed the results from the hours methods into the methods that will determine pay?
In a manner of speaking, yes. Though I think the confusion is coming from the way you describe it and the terminology you use.
It's not entirely clear to me what specific values you're looking for in this case, but it looks like your methods essentially just accept some values, run some calculations, and return some values. Any code which call those functions will then get those returned values and can use them to call other functions. As a contrived example:
private int Method1(int someValue)
{
// perform some calculation, then...
return anotherValue;
}
private int Method2(int someValue)
{
// perform some calculation, then...
return anotherValue;
}
Then consuming code would be able to use those functions to perform larger calculations:
var calculatedValue = Method1(5);
var furtherCalculatedValue = Method2(calculatedValue);
This essentially "feeds the results" of the first function into the second function, in the sense that the result of the first function is then used as an input for the second function. The functions don't have any knowledge of each other, they don't "feed data to each other", in this case they simply return values based on calculations. Consuming code can choose to use the result of one function as a parameter to another function.
You do need to read more on programming and how/why we have methods that return values that the ones you mentioned above. Using your code above you'll want to use their values like this:
// basePayHours is the decimal amount returned by DetermineBasePayHours.
var basePayHours = DetermineBasePayHours(parhoursWorked);
// overTimeHours is the decimal amount returned by DetermineOverTimeHours.
var overTimeHours = DetermineOverTimeHours(parHoursWorked, parCategory);
// basePayAmount is the decimal amount returned by CalculateBasePayAmount.
var basePayAmount = CalculateBasePayAmount(basePayHours, parCategory);
delegate can also be used when a method is needed from another one .
I've been doing an app since few days ago but it's wrong and I do not know why.
I've done the same operation in various ways. I've searched here on the blog, but I still get the incorrect result.
I hope you can help me:
I'm calculating the ** Mean and Standard Deviation**. The Mean is OK. The Standard Deviation is wrong. This is my code:
LinkedList<Double> lista = new LinkedList<Double>();
int contador = 0;
private void btnAgregar_Click(object sender, EventArgs e)
{
lista.AddLast(Convert.ToDouble(txtNum.Text));
MessageBox.Show("Se agregó el número: " + txtNum.Text);
contador++;
txtNum.Text = "";
txtNum.Focus();
}
Double media;
Double desviacionE = 0;
Double suma = 0;
private void btnCalcular_Click(object sender, EventArgs e)
{
media = 0;
calculaMedia();
calculaDesviacionE();
}
public void calculaMedia()
{
foreach (var item in lista)
{
String valorItem = item.ToString();
suma = suma + Convert.ToDouble(valorItem);
}
media = suma / contador;
txtMedia.Text = "" + media;
}
public void calculaDesviacionE()
{
Double average = lista.Average();
Double sum = 0;
foreach (var item in lista)
{
sum += ((Convert.ToDouble(item.ToString()))*(Convert.ToDouble(item.ToString())));
}
Double sumProm = sum / lista.Count();
Double desvE = Math.Sqrt(sumProm-(average*average));
txtDesv.Text = "" + desvE;
}
I hope You can help me!
Thank You
Following the rules for standard deviation found at http://en.wikipedia.org/wiki/Standard_deviation
LinkedList<Double> list = new LinkedList<Double>();
double sumOfSquares = 0;
double deviation;
double delta;
list.AddLast(2);
list.AddLast(4);
list.AddLast(4);
list.AddLast(4);
list.AddLast(5);
list.AddLast(5);
list.AddLast(7);
list.AddLast(9);
double average = list.Average();
Console.WriteLine("Average: " + average);
foreach (double item in list)
{
delta = Math.Abs(item - average);
sumOfSquares += (delta * delta);
}
Console.WriteLine("Sum of Squares: " + sumOfSquares);
deviation = Math.Sqrt(sumOfSquares / list.Count());
Console.WriteLine("Standard Deviation: " + deviation); //Final result is 2.0
You need to subtract the average before squaring.
// Population Standard Deviation
public void populationStandardDev()
{
Double average = lista.Average();
Double sum = 0;
foreach (var item in lista)
{
Double difference = item - average;
sum += difference*difference;
}
Double sumProd = sum / lista.Count(); // divide by n
Double desvE = Math.Sqrt(sumProd);
}
// Standard deviation
public void standardDev()
{
Double average = lista.Average();
Double sum = 0;
foreach (var item in lista)
{
Double difference = item - average;
sum += difference*difference;
}
Double sumProd = sum / (lista.Count()-1); // divide by n-1
Double desvE = Math.Sqrt(sumProd);
}
The formula depends on the set of data you have.
Is it the entire population? Then you should use the Population Standard Deviation (divisor: n).
Is the data a sample of a set? Then you should use the Sample Standard Deviation (divisor: n - 1)
You may find an easier-to-understand guide here: Laerd Statistics - Standard Deviation, which also has a handy Calculator for both solutions.
So, it is as #Greg answered, though I would first check if the list holds any values to avoid division by zero.
double stdDeviation = 0;
if (lista.Any())
{
var avg = lista.Average();
var sumOfSquares = lista.Sum(item => Math.Pow(item - avg, 2));
stdDeviation = Math.Sqrt(sumOfSquares / [divisor goes here]);
}
return stdDeviation;
Where the divisor be lista.Count() for population or (lista.Count() - 1) for samples.