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 ;-)
Related
Let's say I have 21875 as totalQuantityNumber.
I need to split the totalQuantityNumber on multiple days in a for loop ex. first day 20000 and the second day 1875.
Inside my for loop at the end I do a sum of the splitted quantity so I can verify later if the splitting is correct ex. totalSplittedQuantity += splittedQuantity.
At the end of my splitting I verify if the total sum of my splitted products number is the same with the initial planned total products number ex. totalQuantityNumber== totalSplittedQuantity which it should be 21875 == 21875 but I am always off by one number when the number is odd ex. 21875 == 21874. I tried to make the division decimal and round it up at the end but the problem still persists and some of the times the result is over by one as well ex. 21875 == 21876.
This is my division inside the loop:
splittedQuantity = splittedDiffDuration * totalQuantityNumber/ totalDuration;
totalDuration and splittedDiffDuration are in minutes ex. totalDuration = 120; splittedDiffDuration = 60;
Basically I loop through each day from a DateTime interval (startDate, endDate) ex. Monday to Tuesday - splitting the quantity for each day for the duration they were planned ex. let's say on Monday its planned 60 minutes to produce X quantity and on Tuesday the same, 60 minutes to produce the rest of the quantity.
I am new to programming and not so good at math. What am I doing wrong with my division?
Regardless of numbers type (integer, decimal, floating point) there will be an error due to rounding or number representation.
To achieve what you want, you need to calculate the last proportion as the difference between total and the sum of all previous proportions.
E.g., given this total and this percentage:
Total: 100
Day 1: 30%
Day 2: 17&
Day 3: 53%
proportions will be:
Day 1: 100 * 30% = 30
Day 2: 100 * 17% = 17
Day 3: Total - (Day1 + Day2) = 100 - (30 + 17) = 53.
This, of course, gives you approximate result for the last one, but it's the only way to get this expression to be always true:
(Day 1 + Day2 + Day3) = Total
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);
}
}
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
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;
For accounting program I need to divide a price by 3 so it can be shared over 3 months
For example 9€
3€ first month
3€ second month
3€ third month
Now this would be price/3
But what if the number is 10?
3,33€ first month
3,33€ second month
3,33€ last month
3,33€*3 =€9.99
One cent has gone missing.
How can I make it so the ouput would become 3,33€ , 3,33€ , 3,34€?
You need to ask the accountant what they would want here. That's an important thing to do in software development: ask the users.
Normally, for stability, you would subtract the amounts paid from a balance account, and put checks in to ensure that the balance falls to zero.
And don't ever use a floating point data type when building accounting software. Floating point precision will bite you. Use a currency type instead.
You could set the last by making up the difference, instead of via the same calculation as the rest. In pseudocode:
normalMonthPrice = RoundToTwoPlaces(totalPrice / months);
lastMonthPrice = totalPrice - (normalMonthPrice * (months - 1));
As Bathsheba said, ask your users first.
Here's a technique that I've used often in such scenarios. This method will ensure the most even distribution, with the upward bias toward the end. For example, if you call DivvyUp(101, 3), you'll get 33.66, 33.67, 33.67. Notice that the difference isn't just made up for at the end. Instead, each value is computed according to what's left, not what was started with.
public static double[] DivvyUp(double total, uint count)
{
var parts = new double[count];
for (var i = 0; i < count; ++i)
{
var part = Math.Truncate((100d * total) / (count - i)) / 100d;
parts[i] = part;
total -= part;
}
return parts;
}
Congratulations, you've found out why the computing world isn't as simple as "put math on it"-
The easiest solution would be to divide by 3, round to two decimal places, and use that value for the first two months, and original - 2 * perMonth for the rest.