Adding user input into equation through a variable possible? (C#) - c#

I apologize if this is a really simple solution...
So I'm trying to get an Ending Balance from 4 inputs, those being
Starting Balance
Number of months that have elapsed
User Specified yearly interest rate
and a optional monthly contribution that the user can put in. This is what I would imagine the equation to be
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
Everything is fine until the compiler states that Use of unassigned local variable 'contribution' This really confuses me because at the comment at the top of the code I have stated that contribution will be an int.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void calculateButton_Click(object sender, EventArgs e)
{
// Constant for the monthly interest rate.
const decimal INTEREST_RATE = 0.005m;
// Local variables
decimal balance; // The account balance
int months; // The number of months
int contribution;
int count = 1; // Loop counter, initialized with 1
decimal yearly;
// Get the starting balance.
if (decimal.TryParse(txtStartBalance.Text, out balance))
{
// Get the number of months.
if (int.TryParse(txtMonths.Text, out months))
{
// Get the yearly interest rate
if (decimal.TryParse(txtYearly.Text, out yearly))
{
//Get monthly contribution
if (int.TryParse (txtMonthly.Text, out contribution));
}
// The following loop calculates the ending balance.
while (count <= months)
{
// Add this month's interest to the balance.
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
// Display this month's ending balance.
if (rdoEnglish.Checked == false)
lstDetails.Items.Add("ʻO ka pale hope " + "no ka mahina " + count + " ʻO " + balance.ToString("c"));
else
lstDetails.Items.Add("The ending balance for " + "month " + count + " is " + balance.ToString("c"));
// Add one to the loop counter.
count = count + 1;
}
// Display the ending balance.
txtEnding.Text = balance.ToString("c");
Again thank you for taking the time to help me.

This really confuses me because at the comment at the top of the code I have stated that contribution will be an int.
Yes but you have not assigned a value to the variable in at least one path your code can take. (Specifically if int.TryParse (txtMonthly.Text, out contribution)); fails) And then you try to use contribution in the line:
balance = contribution + balance + (INTEREST_RATE * balance) + (yearly * balance);
You need to assign a value to contribution before you use it. Think about what contribution is supposed to represent and assign it to a value accordingly

Try to declare your variables Like below:
decimal.TryParse(txtStartBalance.Text, out decimal balance);
it is better to make a checkbox for the contribution field (txtMonthly) and set its visibility to Checkbox.checked property so if the user wants to set the optional contribution value, has to check the checkbox to write it down.
Also using that ifs in your code is useless until you throw Exceptions when those TryParse methods retrun false and warn the user to try again with right inputs.

Related

How to modify Start method variables in the Update method : Unity

I'm just having a little trouble figuring out how to modify a set variable in the Start method within the Update method. Example:
void Start()
{
// We know what min and max are, so we will set their value instead of updating later on (when something happens, etc.)
int max = 1000, min = 1;
int guess = (min + max) / 2;
Debug.Log("Welcome to Number Wizard");
Debug.Log("Pick a number...");
Debug.Log("The highest number you can pick is: " + max);
Debug.Log("The lowest number you can pick is: " + min);
Debug.Log("Tell me if your number is higher or lower than my guess: " + guess);
Debug.Log("Push up = Higher, Push low = Lower, Push Enter = Correct!");
}
// Update is called once per frame
void Update()
{
foreach (KeyCode single_key in control_keys)
if (Input.GetKeyDown(single_key))
{
/*Debug.Log(single_key + " key pressed!");*/
if (single_key == KeyCode.UpArrow)
{
Debug.Log("It's higher? Okay, I'll guess higher.");
}
else if (single_key == KeyCode.DownArrow)
{
Debug.Log("It's lower? Okay, I'll guess lower.");
}
else if (single_key == KeyCode.Return)
{
Debug.Log("I got it !");
}
}
}
I want to update the guess within the Update loop method, but if I try to do something like this when the guess is too low:
min = guess + 1;
I get this error:
The name 'min' does not exist in the current context.
If anybody has experience in Unity and could help me out that would be much appreciated.
Note: I know I could create a global variable (like my control_keys array), but I thought there must be a way to not just assign a bunch of global variables
Anything you declare inside of a method
- or to be exact in general a code block - is a "local variable" and only exists within this method's (code block's) scope.
(See e.g. c# variable scopes for more information.)
Just make them class fields by declaring them outside of Start
// You also can directly define fields with a default value.
int max = 1000;
int min = 1;
int guess;
private void Start ()
{
guess = (min + max) / 2;
}

Errors in library fee code using multiple methods

I'm making a library program that asks for users to input the amount of books checked out and the amount of days they are over due. If its under or equal to 7 days they are charge 10 cents for each book over due after 7 days its 20 cents for each book. We are supposed to use more than one method and I get two errors:
Use of unassigned local variable 'totalCharge'
There is no argument given that corresponds to the required formal parameter 'daysOverdue' of Program.charge(double,double,double)'
I think I know what the first error means but I thought I already declared it a variable in the first line.
Here's the code so far:
static void Main(string[] args){
double totalCharge;
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are
overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your total charge for {0} days overdue is {1}.",
daysOverdue, totalCharge.ToString("C"));
Console.ReadKey();
totalCharge = charge();
}
private static double charge (double daysOverdue, double booksChecked,
double totalCharge)
{
if (daysOverdue <= 7)
{
return totalCharge = booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + (booksChecked) * (daysOverdue - 7)
* (.20);
}
}
}
}
Your code has a number of problems, which I'll review here. My corrections are at the end of this answer. I recommend putting your code and mine side by side and reviewing the differences carefully.
First, you cannot read the value out of a variable before you have assigned a value. You must assign something to it first.
You need to call charge(...) before printing out the value of totalCharge.
Second, you don't need to pass the value of totalCharge to your charge(...) method: it returns the total charge! So remove that parameter entirely.
Third, you need to pass parameters to the charge method.
Fourth, you had some formatting problems. Please review my code to see how I've formatted my code differently. If a line of code is continued onto the next line, use indentation to reflect this. According to C# conventions, function names should be capitalized.
Lastly, this isn't necessarily a problem, but it doesn't look 'right': in two places, you are assigning Convert.ToInt32(...) to a double. Why? Those should be integers.
static void Main(string[] args)
{
Console.WriteLine("Please enter the number of books checked out.");
double booksChecked = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please enter the number of days they are overdue.");
double daysOverdue = Convert.ToInt32(Console.ReadLine());
// assign before printing out value
// pass the two parameters into the function
double totalCharge = Charge(daysOverdue, booksChecked);
Console.WriteLine("Your total charge for {0} days overdue is {1:C}.",
daysOverdue,
totalCharge);
Console.ReadKey();
}
private static double Charge(double daysOverdue, double booksChecked)
{
if (daysOverdue <= 7)
{
return booksChecked * daysOverdue * .10;
}
else
{
return (booksChecked * .70) + booksChecked * (daysOverdue - 7) * (.20);
}
}

How do I calculate a for loop to display in a listbox where the first loop is user input but the remaining iterations are calculated?

I am trying to create a loop that will calculate inside a listbox but run the actual calculation after the first statement and compound the remaining...
Here is my code:
// Count Loop
int numdays;
numdays = 1;
// Declare and Assign Variables
double organism, daysmultiply, dailyincrease;
organism = double.Parse(OrganismTextBox.Text);
dailyincrease = double.Parse(DailyIncreaseTextBox.Text);
daysmultiply = double.Parse(DaysMultiplyTextBox.Text);
ResultsListBox.Items.Clear();
// Need to have daily increase texbox formatted as a percentage - unsure how
for (numdays = 0; numdays <= daysmultiply; numdays++)
{
ResultsListBox.Items.Add(" Day " + numdays + " Popualtion is " + (organism * dailyincrease));
numdays = numdays++;
}
The result of the calculation is a loop that calculates .6 each time it iterates. I am trying to figure out how to compound the loop each time.
Can someone please help?
Your values don't "compound", because you do nothing in the loop that would cause that to happen, i.e. to change the values of the variables involved in calculating your values.
Your loop has other issues as well: you increment the loop index twice for each iteration; and you unnecessarily reassign the result of the post-increment operator back to the variable (the whole point of the operator is to do that assignment implicitly).
You probably want a loop that looks more like this:
for (numdays = 0; numdays <= daysmultiply; numdays++)
{
ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
organism = organism * dailyincrease;
}
or possibly:
for (numdays = 0; numdays <= daysmultiply; numdays++)
{
ResultsListBox.Items.Add(" Day " + numdays + " Population is " + organism);
organism += organism * dailyincrease;
}
The first example simply multiplies the organism value by the dailyincrease value. The second example does that multiplication and then adds the result to the current organism value. It's not clear from your question which is appropriate; it would depend on what the actual meaning of dailyincrease is. That is, if it's strictly the scale applied each day, then the first example is correct. If it's a representation of the percentage change (e.g. the 0.6 to which you refer means that the population increases 60% each day), then the second example is correct.

Calculating the number of notes an ATM can dispense

I was trying to create a program that will display the imputed amount and the number of $10 and $1 notes that an ATM can dispense but it will not display correct amount of $1 notes.
int amount = int.Parse(txtAmount.Text);
int tenNotes=0, oneNotes=0;
CalculateNotes(amount, ref tenNotes, ref oneNotes);
private void CalculateNotes( int amount, ref int tenNotes, ref int OneNotes)
{
tenNotes = amount /10;
OneNotes = amount - amount % 10;
rtbDisplay.AppendText("Ammount is " + amount + "Ten notes is" + tenNotes + "One notes is" + OneNotes);
}
This is the output I have tried different method of calculation for $1 notes but it does not work.
Am I supposed to use out instead of ref or is there an error in my calculation? Thank you for any help.
You should change this line
OneNotes = amount - amount % 10;
to this one
OneNotes = amount - (tenNotes * 10);
and please reconsider your using of int.Parse to read the input from the textbox. If your user types an invalid integer value you get an exception. This exception could be easily avoided using Int32.TryParse
Finally, I suggest also to use the out keyword for your parameters instead of ref.
See When to use ref vs out
An alternate to the solution that Steve gave, you could also do the following:
Change:
OneNotes = amount - amount % 10;
to:
OneNotes = amount % 10;
Additional Alternate -
It should be noted that what you are trying to do is already a pre-existing function in the System.Math library. As such, you can replace the following code block:
tenNotes = amount /10;
OneNotes = amount - amount % 10;
with:
tenNotes = Math.DivRem(amount, 10, out OneNotes);

Error Reading User Input into Array

So I'm intentionally overcomplicating a homework assignment I was given because I was bored and wanted to learn more about c#. The original assignment is as follows:
"Compute the average of five exam scores ranging between 50 and 90. Declare and perform a compile-time initialization with the five values. Use a constant to define the number of scores. Display all scores and the average value formatted with no digits to the right of the decimal."
So I decided rather than just putting the 5 scores in, I'd allow the user to input them into an array and then calculate it from that.
Console.WriteLine("Enter 5 test scores between 50 and 90:");
int i = 0;
double total = 0;
double[] Scores;
Scores = new double[5];
while (i < 5)
{
Console.WriteLine("Input Score " + (i + 1) + ":");
String input = Console.ReadLine();
Scores[i] = double.Parse(input);
total += Scores[i];
i++;
}
Console.WriteLine("The average of the scores is: " + (total/5));
The issue is that the Scores[i] = double.Parse(input); is throwing an error saying that the input is in the wrong format. So the program won't even run to let me put IN an input, but it says the input format is incorrect.
Any suggestions? I'm probably missing something obvious.
EDIT: Ok, so what ended up working was changing the code to
Console.WriteLine("Input Score " + (i + 1) + ":");
Scores[i] = double.Parse(Console.ReadLine());
total += Scores[i];
i++;
Not sure what it actually changed but it seems to work pretty flawlessly!

Categories