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);
}
}
Related
I'm wondering if someone can help me with decimals? Im going to make a program there can wright price and how much you paid, and then get a change back, but i need to add decimals. The decimals have to round up or down, so if it is 0,11 it goes to 0, if it is o,20 it goes to 0,25. So it will round up to either 0,25, 0,50, 0,75 and later on 1. The change have too also show in which cash you get back, so like 100 bucks, 500 bucks, 50 bucks if you know what i mean. I dont know how to do. This is how long i come:
using System;
namespace inlämninguno
{
class Program
{
// Starting point of my "Change" program
static void Main(string[] args)
{
Console.WriteLine(Subtract()); // adding a subract variable in the beginning of the code
Console.Read();
}
// Using the double datatype to for the decimals
public static double Subtract()
{
Console.WriteLine("Price?"); // how much it costs
string number1Input = Console.ReadLine();
Console.WriteLine("Paid?"); // how much the customer pays
string number2Input = Console.ReadLine();
double prince = Convert.ToDouble(number1Input);
double paid = Convert.ToDouble(number2Input);
// This is for the subtracting part
double num1 = double.Parse(number1Input);
double num2 = double.Parse(number2Input);
double result = num2 - num1; // this is so the console subtracts the values, have to put num2 first so the output isn't negative
Console.Write("Your change is " + result + ":"); // Output "Your change is ..."
return result; // A method that gives the right output of the code
}
}
}
Can someone please help me? Im stuck :D
I tried to convert to double and lots of stuff, but I don't know how to do now.
I have a private method named RentingOrBuying(); that gathers information about the property price and interest rate. I want to create another private method that calculates the monthly home loan repayment but I need the information in RentingOrBuying().
Ive tried using get and set methods but the initialization doesn't seem to work. Maybe I did it wrong. Any help is appreciated. I am calling all the methods in the main class. Is it worth leaving them private or should I be making the methods public. How would you go about this?
//this method uses the information gathered in RentingOrBuying and calculates the monthly home loan repayment
private static void CalculateMonthlyLoanAmount()
{
//accumulated amount = propertyPrice(1 + interestRate)^monthsToRepay
double repaymentAmount = propertyPrice(1 + interestRate);
}
//A method that asks whether the user is buying or renting accommodation and gathers necessary information
private static void RentingOrBuying()
{
Console.WriteLine("Are you going to be renting accommodation or buying a property? \n Please enter either [rent] or [buy]");
//variable to store user input
string buyingRenting = Console.ReadLine();
if (buyingRenting.ToLower() == "rent")
{
Console.WriteLine("We see you want to rent, please can you enter the monthly rental amount: ");
//variable that stores the monthly rental amount.
double monthlyRental = double.Parse(Console.ReadLine());
}
else
{
Console.WriteLine("So you've chosen to buy, I will just need the following ionformation:");
Console.WriteLine("Please enter the purchase price of property: ");
//variable stores the price of the property the user wants to buy
double propertyPrice = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the total deposit: ");
//variable stores the total deposit
double totalDeposit = double.Parse(Console.ReadLine());
Console.WriteLine("Please enter the interest rate (percentage): ");
//variable store the interest rate in percentage form
int interestRate = Int32.Parse(Console.ReadLine());
Console.WriteLine("Please enter the number of months to repay: ");
//variable stores the amount of months to repay
int monthsToRepay = Int32.Parse(Console.ReadLine());
}
}
you should take any variables needed as input parameters, and return any results from the calculations, i.e.
private static double CalculateMonthlyLoanAmount(double interestRate, double propertyPrice)
{
// do whatever calculation you need do to here
// return the result
return result;
}
More complex scenarios would involve encapsulating the variables in a class, to avoid needing to specify them if you call a method multiple times, or multiple methods share many of the variables.
public static int addIntNumbers()
{
int input = int.Parse(Console.ReadLine());
int sum = 0;
while (input !=0)
{
sum += input % 10;
input /= 10;
Console.WriteLine(sum);
}
return sum;
}
I don't understand this syntax: After the while condition, sum += input % 10, which basically means sum = sum(which is 0) + input % 10, so lets say I input 24 so the sum of this should be 4, I think ?
And then the second line which I have no idea what it is even doing.
Any suggestions ?
The best way might be to add comments. However I can already tell that whoever wrote this, did not know what he as doing. For starters, there were not comments, the naming is abysmal and the I/O is actually handeled inside the function.
//The name is not right. This is not a proper sum function
//I think it is getting a sum of all digits in the input
public static int addIntNumbers()
{
//Get a input from the user, parse it to int
//That really belons outside. Just the int in per argument
int input = int.Parse(Console.ReadLine());
//Initialize sum to 0
int sum = 0;
//Input is also used as sort of "running variable".
//The loop will break if input reaches 0
while (input !=0)
{
//sum = sum + input % 10
//It tries to divide input by 10, get's the rest, then adds that rest to sum
sum += input % 10;
//Divide input by 10. Note that all decimal parts will be dropped
//That means it will reach 0 invariably
input /= 10;
//Output the current sum for debugging
Console.WriteLine(sum);
}
//The function returns
return sum;
}
Your code calculates digit-by-digit sum of an integer (the sum is positive if input is positive, negative if input is negative).
If you are a C# beginner, this might help you:
while (input !=0)
{
sum = sum + (input % 10); //sum = sum + remainder of division by ten (separation of least significant digit)
input = input / 10; //input is integer-divided by ten, which results in discarding of the least significant digit
Console.WriteLine(sum);
}
If you don't understand, get familiar with a difference between
4/6
and 4.0/6.
The first one is integer division, the other is floating point division.
Some things to help you understand what's going on here:
First, assuming you're in Visual Studio, you can set a break point in your code by clicking to the left of the line number, in the margin. A red dot will show up and when your code hits that point, it will pause. While paused, you can look at the "Locals" tab or hover over variable names in your code to see what values are at that point in time. You can then use F10 to step forward one line at a time and see how things change.
Second, the /= operator is similar to the += operator, except with division. So, "x /= 10" is exactly the same as "x = x / 10".
This program is adding up each digit of the number you type in by getting the ones digit, adding it to sum, then dividing the number by 10 to get rid of the old ones digit.
The program I am creating prompts the user to enter an amount of months, the amount of work absences he/she has had in each month, and the amount of absences allowed per month. It is supposed to calculate the average amount of work absences by an employee as well as the amount of times that he/she went over the max absences allowed.
I was able to calculate the average with an array loop but was having issues with the times he/she has gone over the max absences. I am using the binary search method but have trouble outputting the specific amount of months that the employee has gone over the allowed absence amount.
This is my current code for that section:
for (int i = 0; i < numbOfAbsences.Length; i++)
{
sum += numbOfAbsences[i];
averageAbsences = (sum / numbOfMonths);
Console.WriteLine("Employee was absent " + averageAbsences + " times per month.");
}
a = Array.BinarySearch(numbOfAbsences, maxAbsences);
if (a >= maxAbsences)
{
}
I am unsure of what would go under the last set of brackets, as I am not trying to point out whether the max amount was exceeded but rather the amount of times that it was.
Thank you for the help in advanced.
First off, the question is not clearly stated. It boils down to this:
"What's a good way to take an int array of sums and divide them all by a count to produce a double array of averages? Also, how can I count the values of an int array greater than a threshold? (Here's what I've got so far: )"
Second, the code snippet is very confusing. More precisely... It's not indented correctly. Not all of the variables used are defined, so we have to guess what they are. The variable names aren't very descriptive, so one has to look at how each variable is used to understand it. Most importantly however, this is no encapsulation. No objects, no functions... just raw code that you need to read every line of very carefully to understand.
Contrast the snippet with this:
using System;
using System.Linq;
namespace ArraySearch_StackOverflow
{
class Program
{
static void Main(string[] args)
{
int[] employeeAbsencesEachMonth = new int[] { 1, 2, 3, 4, 5, 6 };
int maxAbsencesAllowedPerMonth = 3;
double averageAbsencesPerMonth = GetAverageAbsencesPerMonth(employeeAbsencesEachMonth);
Console.WriteLine($"Employee's Average Absences Per Month: {averageAbsencesPerMonth}"); /* 3 */
int numTimesMaxAbsencesExceeded = GetNumMaxAbsencesViolations(employeeAbsencesEachMonth, maxAbsencesAllowedPerMonth);
Console.WriteLine($"Number of Times Employee Exceeded Max Absence Limit: {numTimesMaxAbsencesExceeded}"); /* 3 */
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
private static double GetAverageAbsencesPerMonth(int[] employeeAbsencesEachMonth)
{
// ???
throw new NotImplementedException();
}
private static int GetNumMaxAbsencesViolations(int[] employeeAbsencesEachMonth, int maxAbsencesAllowedPerMonth)
{
// ???
throw new NotImplementedException();
}
}
}
This snippet is extremely clear. Even without a description, it's immediately apparent what's being asked, and how to tell if an answer is correct. Because the questions have been translated into a function signature and the context has been translated into a driver in which the functions are called, complete with setup and an expected result.
Handily, this implies a simple format for the answer, creating a good chance you can copy-paste it directly into your code:
private static double GetAverageAbsencesPerMonth(int[] employeeAbsencesEachMonth)
{
return employeeAbsencesEachMonth.Sum() / employeeAbsencesEachMonth.Length;
}
private static int GetNumMaxAbsencesViolations(int[] employeeAbsencesEachMonth, int maxAbsencesAllowedPerMonth)
{
return employeeAbsencesEachMonth.Count(x => x > maxAbsencesAllowedPerMonth);
}
I'm trying to check if the user's response is a double or an int, but the int is specific, whereas the double is not, as I probably made a right mess of explaining it, here's the code:
Console.WriteLine("\n 2) Q: How old is Sally? \n");
int nSallyAge = Convert.ToInt32(Console.ReadLine());
double dSallyAge = Convert.ToDouble((nSallyAge));
if (nSallyAge == 62 || dSallyAge == 62.0)
{
// Increase Score
sUser1Score++;
Console.WriteLine("\n A: Correct, Sally's age is 62, you have been awarded 1 point. \n");
Console.ReadLine();
}
What I'm trying to do, is instead of dSallyAge HAS to equal 62.0, it just has to equal any double figure.
I would approach this problem by first creating a method that gets a double from the user (that will, of course, also accept an int). This removes error handling from your main code.
NOTE in the code below, Math.Truncate can be replaced by Math.Floor, with the same result:
private static double GetDoubleFromUser(string prompt)
{
double input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again.");
}
return input;
}
Then, in my main code, I would get the number from the user, and use the Math.Truncate method to just read the first part of the double passed in by the user (this is what it sounds like you want to do). This means that if the user enters anything from 62 to 62.0 to 62.999, it will truncate the result to '62':
double nSallyAge = GetDoubleFromUser("2) Q: How old is Sally? ");
if (Math.Truncate(nSallyAge) == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Other alternative ways to use this are:
int sallyAge = Math.Truncate(GetDoubleFromUser("2) Q: How old is Sally? "));
if (sallyAge == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Or, you could use an input function that returns an int in the first place:
private static int GetIntFromUser(string prompt)
{
return Math.Truncate(GetDoubleFromUser(prompt));
}
In your code above, you are converting the input to an integer and then converting the int result to a double.
Assuming that you are only allowing numerical values to be entered, why not try something like this. This will identify if the input contained decimals or not:
string input = Console.ReadLine();
int iSallyAge;
double dSallyAge;
if (!Int32.TryParse(input, iSallyAge))
{
dSallyAge = Double.Parse(input);
}
You should be using Double.TryParse to parse the user input to a double and then test that value to see whether it's equal to 62.0.
double age;
if (double.TryParse(Console.ReadLine(), out age) && age == 62.0)
{
// age is 62.
// ...
}