I am trying to make a loop that calculates number of organisms over time, but I am stuck on how to make the loop update. Do I need to put something outside the for loop to update the total organisms?
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
double total_organisms;
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (double.TryParse(organismTextBox.Text, out organisms))
{
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily))
{
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days))
{
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval)
{
//calculate the amount of organisms
total_organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add("after " + i + " days, the amount of organisms is " + total_organisms);
}
Each loop, you are calculating the total_organisms as the sum of organisms plus some percent:
total_organisms = (organisms * (increaseDaily / 100) + organisms);
You are never changing the value of organisms, so total_organisms will be calculated as the same value each loop. You should just updated the value of organisms instead.
Also, you could reduce indentation in your code by changing each if statement to test for parse failure and bail out:
private void calculateButton_Click(object sender, EventArgs e)
{
//declare variables for number of days passed and population
double days;
double organisms;
double increaseDaily;
List<string> errors = new List<string>();
//declare the constants to be used
const int interval = 1;
const int start_days = 1;
//try parse to get amount of starting organisms
if (!double.TryParse(organismTextBox.Text, out organisms)) {
errors.Add("Organisms must be a valid number");
}
//try parse to get the percent daily increase
if (double.TryParse(dailyIncreaseTextBox.Text, out increaseDaily)) {
errors.Add("Daily increase must be a valid number");
}
//try parse to get the number of days passed
if (double.TryParse(daysMultiplyTextBox.Text, out days)) {
errors.Add("Number of days must be a valid number");
}
if (errors.Any()) {
// Display errors to user here (depending on your UI)
return;
}
//for loop to count through the number of days
for (int i = 1; i <= days; i += interval) {
//calculate the amount of organisms
organisms = (organisms * (increaseDaily / 100) + organisms);
//display the amount of organisms after an amount of time
listBox1.Items.Add(
"after " + i + " days, the amount of organisms is " + organisms);
}
}
If you want to keep adding to the total number of organisms:
total_organisms = total_organisms + (organisms * (increaseDaily / 100) + organisms);
Related
I have created a form to arrange a ship hold.
Problem: On multiple times through, it comes back with the decimal point shifted two more spaces. How do I keep it from shifting further?
Code Snippet:
private void btnGetInv_Click(object sender, EventArgs e)
{
//if this is a ship hold, roll percentile to get how much of the ship's total weight capacity is being carried.
if(ShipHold==true)
{
decimal Percentage = 0;
decimal HoldWeight = 0;
LoNum = 1;
HiNum = 100;
DieResult = 0;
Percentage = DieResult + 1 + RollDice.Next(LoNum - 1, HiNum);
WeightAvail = Percentage / 100 * WeightAvail;
HoldWeight = WeightAvail;
RTBItems.Text = "percentage of weight = " + HoldWeight + "\r\n" + RTBItems.Text;
}
WeightAvail is also a decimal. However; LoNum, HiNum, and DieResult are all types int to work with the Random.Next function. It might be best if I can round to the nearest whole number. I'm using Visual Studio 2019.
This was my fix:
HoldWeight = Percentage / 100 * WeightAvail;
//HoldWeight = WeightAvail;
RTBItems.Text = "percentage of weight = " + HoldWeight + "\r\n" + RTBItems.Text;
HoldWeight = 0;
I have a ListForm in C#
The question is when a user clicks on a certain student in the list I want it to find the average, score count and sum.
Code Below:
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
txtTotal.Text = listForm1.SelectedItem.ToString();
}
private void Form1_Load(object sender, EventArgs e)
{
listForm1.Items.Add("Hamish overtonne" + "|" + 39 + "|" + 12 + "|" + 85);
listForm1.Items.Add("Claudia Dye" + "|" + 44 + "|" + 56 + "|" + 85);
listForm1.Items.Add("Mike Layne" + "|" + 12 + "|" + 47+ "|" + 28);
}
That's All I have for now
Here's the code you can use to do that. Just keep in mind to register a SelectedIndexChanged event to your list.
Also keep in mind that using integers, like I did, will create whole numbers, without decimal points.
I've added code comments to explain the process:
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the value from the selected item
string val = listForm1.GetItemText(listForm1.SelectedItem);
// Split the item's value to a string array according to the pipe char
string[] valArray = val.Split('|');
int sum = 0;
int scores = 0;
// Iterate through all possible values and sum it up,
// while keeping count to how many numbers there are:
for (int i = 1; i < valArray.Length; i++)
{
int num = Convert.ToInt32(valArray[i]);
sum += num;
scores++;
}
// Calculate the average.
// Keep in mind using an integer will create a whole number, without decimal points.
int average = sum / scores;
// Place the average and the sum in textboxes
txtAverage.Text = average.ToString();
txtTotal.Text = sum.ToString();
txtCount.Text = scores.ToString();
}
try below code :
private void listForm1_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the value from the selected item
string val = listForm1.GetItemText(listForm1.SelectedItem);
// Split the item's value to a string array according to the pipe char
string[] valArray = val.Split('|');
int sum = 0;
int scores = 0;
int value=0;
// Iterate through all possible values and sum it up,
// while keeping count to how many numbers there are:
for (int i = 1; i < valArray.Length; i++)
{
int.TryParse(valArray[i], out value);
if(value>0){
int num = value;
sum += num;
scores++;
}
}
// Calculate the average.
// Keep in mind using an integer will create a whole number, without decimal points.
int average = sum / scores;
// Place the average and the sum in textboxes
txtAverage.Text = average.ToString();
txtTotal.Text = sum.ToString();
txtCount.Text = scores.ToString();
}
What I need to do is take a time window on a 24hr clock ie: 1000-1100
convert it to seconds, which I can do.
(1000 / 100)*60 = 600
(1100 / 100)*60 = 660
Get 25% of the result(15), which I can also do. (660 / 4)
Add that 25% of additional seconds to the previous end time (1100)
The issue is that I am getting an output of 1100 instead of 1115
The Question is how do I make it output as 1115.
I do use constants to define hour and hundred so no magic numbers, these numbers are just illustrating the math.
//define constants
const int HUNDRED = 100;
const int HOUR = 60;
const int PERCENT = 4;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// recieve start time input
string oldStart = oldStartTime.Text;
int oldTimeIn = int.Parse(oldStart);
// recieve end time input
string oldEnd = oldEndTime.Text;
int oldTimeEnd = int.Parse(oldEnd);
// convert start time to minutes
int hoursStart = (oldTimeIn / HUNDRED) * HOUR;
int minutesStart = oldTimeIn % HUNDRED;
int totalStart = hoursStart + minutesStart;
// convert end time to minutes
int hoursEnd = (oldTimeEnd / HUNDRED) * HOUR;
int minutesEnd = oldTimeEnd % HUNDRED;
int totalEnd = hoursEnd + minutesEnd;
// calulate 25% of travel time ( end - start )
int extraTime = totalEnd - totalStart;
int totalMinutes = (extraTime / PERCENT);
// convert back to hours
int newEndHours = (totalEnd + totalMinutes) / HOUR * HUNDRED;
// out put new end time
newEndTime.Text = $"{newEndHours:d4}";
int newEndHours = (totalEnd + totalMinutes) / HOUR * HUNDRED;
The operation is being done as integers, so the (660 + 15)/100 is coming out as 11. Remember that even if it was casted to doubles, it would result in 11.25, and not 11.15.
You will have to add in another part similar to when you deconstructed the time to handle the minutes part, so
int newEndHours = (totalEnd + totalMinutes) / HOUR * HUNDRED + (totalEnd + totalMinutes) % HOUR;
Ok. So I'm trying to have a program.. where the user enters his salary and then the program will calculate his salary for the next four years with a raise of 2.5% each year.
I feel like I have done this completely wrong, because my loop is only calculating one time.. its not even showing four salary's.. not to mention having them each raised 2.5% each time.
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
for (count = 1; count <= 4; count++)
{
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
label2.Text = Total.ToString("c");
}
txtSalary is whatever the user entered salary is.
label2 is the display of the calculation.
---------------- UPDATE: I have updated the code with the final product. Thanks to everyone for helping out especially Patrick Hofman! You are the best.. I couldn't have done it without you. ------------------------
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal previous = salary;
for (decimal year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
listBox1.Items.Add(sum.ToString("c"));
}
I think you should have something like this:
private void btnDisplay_Click(object sender, EventArgs e)
{
decimal salary = Convert.ToDecimal(txtSalary.Text);
decimal raise = 0.025m;
decimal total = 0;
decimal previous = salary;
listBox1.Items.Add("Start: {0:N2}", salary);
for (int year = 1; year <= 4; year++)
{
decimal sum = previous * (1 + raise);
previous = sum;
total += sum;
listBox1.Items.Add("Year {0}: {1:N2}", year, sum);
}
listBox1.Items.Add("Total: {0:N2}", total);
}
Note I made some changes to the variables. Some were moved to keep them over the for loop.
The steps:
Start with setting the start point (previous) to the salary.
For each year, multiply the previous year's salary with the raise percentage +1.
Set the previous and add that year's salary to the total.
Show the total in the label.
int count;
Salary = Convert.ToDecimal(txtSalary.Text);
for (count = 1; count <= 4; count++)
{
Salary *= 1.025m;
}
label2.Text = Salary.ToString("c");
You need to make sure you're retrieve the salary once at teh beginning and don't overwrite it till the end.
Problem 1: You are declaring the variables inside the forloop.so each time they are initialised with their default values.
Solution 1: inorder to retain their last assigned values you need to move the declaration of the variables outside the loop.
Problem 2: you are not able to see the results/changes as you are updating the label inside the for loop without any delay.so evatually you can only see the last calculated result.
Solution2: You need to either create 4 different labels to show the 4 different results or you need to wait for some time for updating the label results in each iteration by using timer functionality.
Try This: using LabelArray
Label[] lblSalaries = new Label[4];
private void CreateControls()
{
int x = 0, y = 10;
for (int i = 0; i < lblSalaries.Length;i++ )
{
lblSalaries[i] = new Label();
x += 60;
lblSalaries[i].Size = new System.Drawing.Size(50, 30);
lblSalaries[i].Location = new System.Drawing.Point(x,y);
Controls.Add(lblSalaries[i]);
}
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int count;
decimal Raise;
decimal Salary;
decimal Sum;
decimal Total;
CreateControls();
for (count = 1; count <= 4; count++)
{
Raise = Convert.ToDecimal(0.025);
Salary = Convert.ToDecimal(txtSalary.Text);
Sum = Salary * Raise;
Total = Salary + Sum;
lblSalaries[count-1].Text = Total.ToString("c");
}
}
This is an attempt to convert a split string to an int format to display a user input time such as 2:15 meaning 2 hours and 15 minutes. I want to be able to multiply this time period by a dollar rate and add an additional cost. there is a subAmount and then a total both using ToString. Any 'clues' would be appreciated
private void calulateButton_Click(object sender, EventArgs e)
{
string[] item = timeTextBox.Text.Split(':');
int hours, mins, rate, cost;
int.TryParse(item[0], out hours);
Convert.ToInt64(item[0]);
int.TryParse(item[1], out hours);
Convert.ToInt64(item[1]);
int.TryParse(rateTextBox.Text, out rate);
int.TryParse(prescriptionTextBox.Text, out cost);
int prescription = cost;
int totalHours = hours;
subAmountLabel.Text = totalHours.ToString("f2");
int total = (totalHours) * rate + cost;
totalAmountLabel.Text = total.ToString("f2");
}
This is just a shot in the dark at what I think you are trying to do:
TimeSpan ts = TimeSpan.Parse(timeTextBox.Text);
double rate, cost;
double.TryParse(rateTextBox.Text, out rate);
double.TryParse(prescriptionTextBox.Text, out cost);
subAmountLabel.Text = ts.TotalHours.ToString("f2");
double total = ts.TotalHours * rate + cost;
totalAmountLabel.Text = total.ToString("f2");
You code sample seems perfectly valid (except you assign hours twice) but it contains some redundant lines. I fixed issue with hours and mins, got rid of unnecessary variables and instructions and edited total formula to include minutes as well:
private void calulateButton_Click(object sender, EventArgs e)
{
string[] item = timeTextBox.Text.Split(':');
int hours, mins;
int.TryParse(item[0], out hours);
int.TryParse(item[1], out mins);
double rate, prescription;
double totalHours = hours + mins / 60.0;
double.TryParse(rateTextBox.Text, out rate);
double.TryParse(prescriptionTextBox.Text, out prescription);
double total = totalHours * rate + prescription;
subAmountLabel.Text = totalHours.ToString("G");
totalAmountLabel.Text = total.ToString("C");
}