Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So in my C# class, I was asked to;
Write a program that computes the amount of money the computer club will receive from proceeds of their granola bar sales project. Allow the user to enter the number of cases sold and the sale price per bar.Each case contains 12 bars; each case is purchased at $5.00 per case from a local vendor.The club is required to give the student government association 10% of their earnings. Display their proceeds formatted with currency. Write appropriate methods for your solution.
I wrote the program but I am pretty sure the math is not adding up (unless I am screwing up the calculations that I am plugging into my calculator.
Here is my code.
using System;
namespace GranolaBars
{
class Granola
{
static void Main(string[] args)
{
// Give user info on program
Console.WriteLine("The Computer Club buys the cases at $5.00 a case");
Console.WriteLine("The studdent government gets 10% of profit");
Console.WriteLine("Total made from sell is number of cases sold minus 10%");
// Declare the variables
int casesSold;
decimal pricePerBar;
decimal profit;
decimal proceeds;
decimal finalOutCome;
// Set the variables values
casesSold = GetCasesSold();
pricePerBar = GetPricePerCase();
profit = GetProfit(casesSold, pricePerBar);
proceeds = GetProceeds(profit);
finalOutCome = GetFinalOutCome(proceeds, profit);
// The output from the program
Console.WriteLine("The amount cases of sold was: {0} ", casesSold);
Console.WriteLine("The price per bar was {0:C}: ", pricePerBar);
Console.WriteLine("The gross profit is: {0:C}: ", profit);
Console.WriteLine("The student government fees are: {0:C} ", proceeds);
Console.WriteLine("The income minus the student government fees is: {0:C} ", finalOutCome);
Console.ReadKey();
}
public static int GetCasesSold()
// Method that gets the total number of cases sold
{
int CSold;
Console.Write("Enter the number of cases sold: ");
CSold = int.Parse(Console.ReadLine());
return CSold;
}
public static decimal GetPricePerCase()
// Method that gets the price per case of garnola bars
{
decimal PerBar;
Console.Write("Enter the price per bar: ");
PerBar = decimal.Parse(Console.ReadLine());
return PerBar;
}
public static decimal GetProfit(int CasesSold, decimal PricePerBar)
// Method to get the Profit
{
decimal PriceofCase = 5.00M;
decimal Earnings;
Earnings = ((PricePerBar * 12) - PriceofCase);
return Earnings;
}
public static decimal GetProceeds(decimal Profit)
// Method to get the Proceeds
{
decimal StudentGovFunds = .10M;
return (Profit * StudentGovFunds);
}
public static decimal GetFinalOutCome(decimal Proceeds, decimal Profit)
// Method to calculate the final total made from selling granola pars
{
return (Profit - Proceeds);
}
}
Is my program calculating correctly or am I missing what would make it calculate correctly?
This seems to be a problem
I mean you need to times how many cases are sold at least at some point
public static decimal GetProfit(int CasesSold, decimal PricePerBar)
// Method to get the Profit
{
return (((PricePerBar * 12) - PriceofCase) * CasesSold);
}
output
The Computer Club buys the cases at $5.00 a case
The studdent government gets 10% of profit
Total made from sell is number of cases sold minus 10%
Enter the number of cases sold: 2
Enter the price per bar: 10
The amount cases of sold was: 2
The price per bar was $10.00:
The gross profit is: $230.00:
The student government fees are: $23.00
The income minus the student government fees is: $207.00
Related
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.
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);
}
}
I have a homework question that I need some verification on. I got the correct answer for the first part of the question. However, the second part of the question isn't working out so well. I'm not sure if my calculations are off or if the test data is wrong. (it's happened a few times already this year).
We are suppose to design a console application that will solve how many months it'll take to pay off a loan.
I can't use any code I haven't learned yet; just basic code. (no loops, arrays, etc)
The formula is:
N = -(1/30) * ln(1+b/p(1-(1+i)^30)) / ln(1+i)
n = months
ln = log function
b = credit card balance
p = monthly payment
i = daily interest rate (annual interest rate/365)
Test Data for Question 1:
Credit Card Balance: $5000
Monthly Payment: $200
Annual Rate: 0.28
My answer: 38 months
Test Data for Question 2:
Credit Card Balance: $7500
Monthly Payment: $125
Annual Rate: 0.22
Unable to get an answer
My solution:
static void Main(string[] args)
{
decimal creditcardbalance, monthlypayment;
double calculation, months, annualpercentrate;
Console.WriteLine("Enter the credit card balance in dollars and cents: ");
creditcardbalance = decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter the monthly payment amount in dollars and cents: ");
monthlypayment = decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter the annual rate percentage as a decimal: ");
annualpercentrate = double.Parse(Console.ReadLine());
calculation = (Math.Log((1 + (double)(creditcardbalance / monthlypayment) * (1 - (Math.Pow(1 + (annualpercentrate / 365), 30)))))) / (Math.Log((1 + (annualpercentrate / 365))));
months = (-0.033333333333333333) * calculation;
Console.WriteLine("\nIt will take {0:F0} months to pay off the loan.", months);
Console.WriteLine("Goodbye!");
Console.ReadLine();
}
Your problem is that you try to take the logarithm of a negativ number. Thats why you get "NaN" (not a number) as a result.
But why is 1+b/p(1-(1+i)^30) negative in the second example?
Well, that is simple. Because your monthly interest is greater than your monthly payment!
$7500 * 0.22 / 12 = 137.5$
Since your monthly payment is just $125, you will take an infinite amount of months (speak: never) to pay of your debt.
NaN is the programming languages way to represent a non-computable result.
So, you don't have a programming problem, you have a debt problem. Maybe this is a question for money.stackexchange.com ;-)
So I am trying to make a script where the user inputs the number of miles they need to travel and the miles per hour they are traveling and the script outputs the hours and minutes leftover that they must travel. I've been trying to use % to find the remainder of the miles traveled/MPH but it outputs the wrong number. Is there anyway to only get the decimal from two divided numbers? For example, if I do 100/65 I get the output of about 1.538, I want to only use the 0.538. But when I use 100%65 I get 35. Here is my current script for reference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimeCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Travel Time Calculator");
string answer;
//creates variable for the answer
do
//creates loop to continue the application
{
string grade;
//Console.WriteLine(100-(int)((double)100/65)*65);
Console.WriteLine(" ");
Console.Write("Enter miles: ");
Decimal val1 = Convert.ToDecimal(Console.ReadLine());
//converts input to decimal allowing user to use decimals
Console.Write("Enter miles per hour: ");
Decimal val2 = Convert.ToDecimal(Console.ReadLine());
//converts input to decimal allowing user to use decimals
Console.WriteLine(" ");
Console.WriteLine("Estimated travel time");
Console.WriteLine("Hours: " + (((int)val1 / (int)val2)));
//converts values to integers and divides them to give hours traveled
//double floor1 = Math.Floor(((double)val1/(double)val2));
Console.WriteLine("Minutes: " + (Decimal.Remainder((decimal)val1, (decimal)val2)));
//converts values to double and gets the remainder of dividing both values to find minutes
Console.WriteLine();
//enters one line
Console.Write("Continue? (y/n): ");
answer = Console.ReadLine();
//the string is equal to what the user inputs
Console.WriteLine();
}
while (answer.ToUpper() == "Y");
//if y, the application continues
}
}
100/65 is an integer division. What you need is
double d = (100d / 65) % 1;
This will give you 0.53846153846153855
If you want hours and minutes from the initial values then this should do it for you (you may need some explicit casts in there, this is untested)
var result = va1 / val2;
var hours = Math.Floor(result);
var minutes = (result - hours) * 60;
Write code that will:
• Ask the user for their tax code (A or B) and annual salary
• Display the tax the person has to pay for the year. People on tax code A have
to pay 25% of their salary in tax, those on tax code B must pay 30% if their
salary is $45,000 or less, 33% otherwise.
Example:
What is your tax code? A
What is your annual salary? 42560
Tax due $10,640
so my question is how do i do this in Microsoft Visual studio?
I appreciate all the help and comments :)
Start a console project.
Print out with System.Console.Write ("question?"); or System.Console.WriteLine("question?");
Get input with string input = Console.ReadLine();
Convert to required data type using functions like int salary = int.Parse(input)
Process according to the requirement. You will mostly use if to determine which rate to use.
Remember to repeat the question if the input is not correct; eg: not a number, not A or B.
long amount = [get amount];
string taxCode = [get code];
decimal tax =0;
if (taxCode == "A" && amount <= 45000)
tax = 0.25M * amount;
else if (taxCode == "B" && amount <= 45000)
tax = .3M * amount;
else
tax = .33M * amount;
This should do the trick
This should get you started:
float rate;
if(ddl_Code.SelectedValue == "A")
{
rate = .25F;
}
else if(ddl_Code.SelectedValue == "B" && Convert.ToDecimal(tb_Salary.Text) <= 45000)
{
rate = .3F;
}
else
{
rate = .33F;
}
tb_TaxDue.Text = Convert.ToDecimal(tb_Salary.Text) * rate;
This assumes you have a drop down list for Tax Code and two text boxes for Taxes due and salary.