So this is my budget calculator.
It calculates how much i can earn with deposit(% per year), i can add money(earnings) and can decrease money(loosing).
In my code you have to manually tell the size of starting money.
What i need is for example in the beginning i tell my program that starting capital is 500euro. When i use deposit, it become for example 570,50. When i use earnings, i need it to start from 570,50, but in my program it will always ask again, what is your starting capital. I need to do it automatically somehow. Sorry for my bad english and here is the whole code :)
class Program
{
static void Main(string[] args)
{
int menu;
do
{
Console.WriteLine("1 - '%'");
Console.WriteLine("2 - '+'");
Console.WriteLine("3 - '-'");
Console.WriteLine("0 - iziet");
Console.Write("Menu: ");
menu = Convert.ToInt32(Console.ReadLine());
if (menu > 0 && menu < 4)
{
switch (menu)
{
case 1:
{
Console.Write("Noguldamā naudas summu: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("Procentu likme (0 - 100): ");
int b = Convert.ToInt32(Console.ReadLine());
Console.Write("Laiks (gadi): ");
int c = Convert.ToInt32(Console.ReadLine());
double d = Procenti(a, b, c);
Console.WriteLine("\nNaudas summa pēc {0} gadiem būs {1}\n", c, d);
}
break;
case 2:
{
Console.Write("Sakuma nauda: ");
int a = Convert.ToInt32(Console.ReadLine());
Console.Write("Cik nopelnijat: ");
int b = Convert.ToInt32(Console.ReadLine());
double d = Pluss(a, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", d);
}
break;
case 3:
{
Console.Write("Sakuma nauda: ");
double a = Convert.ToDouble(Console.ReadLine());
Console.Write("Cik izterejat: ");
double b = Convert.ToDouble(Console.ReadLine());
double d = Minuss(a, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", d);
}
break;
}
}
else
{
Console.WriteLine();
Console.WriteLine("Ludzu ievadiet ciparus 0,1,2,3 - parejie cipari ir arpus robezham!");
Console.WriteLine();
}
} while (menu != 0);
}
//FUNKCIJASSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS
static double Procenti(double a, double b, int c)
{
for (int i = 0; i < c; i++)
{
a = (a * (b / 100) + a);
}
return a;
}
static double Pluss(double a, double b)
{
return a + b;
}
static double Minuss(double a, double b)
{
return a - b;
}
}
you need to store the value inside a variable.
and before to start the transactions you ask the user for the value :
int menu;
float stored_money;
Console.Write("Enter the Initial Value: ");
stored_money = Convert.ToInt32(Console.ReadLine());
do
{
and in the functions use this variable
static double Pluss(double b)
{
stored_money = stored_money + b;
return stored_money;
}
static double Minuss(double b)
{
stored_money = stored_money - b;
return stored_money;
}
Well, basically it looks like you need to save your balance amount somewhere in your code, because right now you're entering it from console in each menu point.
Something like (note I've omitted most of code):
int menu;
decimal amount;
do
{
.... //your code
case 1:
{
Console.Write("Noguldamā naudas summu: ");
amount = Convert.ToDecimal(Console.ReadLine());
.... //your code
decimal d = Procenti(a, b, c);
amount += d;
}
case 2:
{
Console.Write("Cik nopelnijat: ");
decimal b = Convert.ToInt32(Console.ReadLine());
amount = Pluss(amount, b);
Console.WriteLine("Tagadejais budzhets ir: {0} euro", amount);
}
.... //your code
} while (menu != 0);
And later in all cases you should not enter amount, but use that saved value and modify it according to menu point task.
Or maybe you even should introduce new menu point to set initial amount and don't enter it in point 1 (if point 1 can be called multiple times) - it depends on your calculator logic and it's up to you.
Note - it's better to use decimal rather that int and double for financial calculations as it is designed to store full possible precision.
Related
This is a simple calculator. It performs calculations. However, every time it calculates I save that total and add it to a running total. But when I type in undo, the running total disappears and the previous calculation is not subtracted from the running total. Can someone please help me? This is suppose to be in memento format. So when I undo, a stack is removed or a total from a previous calculation. I am struggling with that.
class Calculator
{
public Stack<double> result= new Stack<double>();
double total = 0;
public void Add(double a, double b)
{
total += a + b;
Console.WriteLine("Sum:{0}", total);
result.Push(total);
}
public void Sub(double a, double b)
{
total += a - b;
Console.WriteLine("Difference:{0}", total);
result.Push(total);
}
public void Mul(double a, double b)
{
total += a * b;
Console.WriteLine("Product:{0} ", total);
result.Push(total);
}
public void Div(double a, double b)
{
if (b!=0)
{
total += a / b;
Console.WriteLine("Quotient:{0}", total);
result.Push(total);
}
else
{
Console.WriteLine("Error: Cannot divide by 0");
}
}
double GetTotal()
{
return total;
}
void Undo()
{
if (result.Count==0)
{
Console.WriteLine("UNDO IS NOT AVAILABLE");
}
Console.WriteLine("Running total:{0}", total);
}
void clear()
{
while (result.Count !=0)
result.Pop();
total = 0;
Console.WriteLine("Running total:{0}", total);
}
static int Main()
{
Calculator cal=new Calculator();
string line="";
while (true)
{
Console.WriteLine("Enter (Clear, Undo, Exit, Expression):");
if (line.ToLower() == "exit")
break;
else if (line.ToLower() == "undo")
cal.Undo();
else if (line.ToLower() == "clear")
cal.clear();
else
{
double a, b;
Console.WriteLine("Write the first number");
double.TryParse(Console.ReadLine(), out a);
Console.WriteLine("Write the second number");
double.TryParse(Console.ReadLine(), out b);
Console.WriteLine("Write the operand (+, -, /, *)");
char.TryParse(Console.ReadLine(), out char c);
if (c == '+')
cal.Add(a, b);
if (c == '-')
cal.Sub(a, b);
if (c == '*')
cal.Mul(a, b);
if (c == '/')
cal.Div(a, b);
}
}
return 0;
}
There are a couple things you need to fix here.
First, you never assign anything to line, so your code immediately falls into the else block for "Expression". So not only is Undo() not working, but I don't see how the Clear() or Exit() methods could be working either. Something like this will help with that by assigning to line:
while (true)
{
Console.WriteLine("Enter (Clear, Undo, Exit, Expression):");
line = Console.ReadLine();
if (line.ToLower() == "exit")
break;
//Rest of the code left out for simplicity...
}
Note that this considers invalid input as "Expression" and false down the else path, so you might want to consider explicitly checking for line.ToLower() == "expression" and giving an error message otherwise.
Also consider changing to a switch statement. It's not required by any means, but a little easier to maintain and read, IMO. You should also probably do a case-insensitive Equals() with this overload rather than converting the input to lowercase.
As for the actual implementation of your Undo() method, since your last action is just one item down on the Stack, just Pop() the top item off and Peek() at the Stack for your previous total:
void Undo()
{
if (result.Count==0)
{
Console.WriteLine("UNDO IS NOT AVAILABLE");
}
result.Pop(); //Remove current total from last expression
total = result.Peek(); //Take previous total
Console.WriteLine("Running total:{0}", total);
}
This should get you most of the way there. They may be other things that you'll need to fix as well. I did test the undo and clear functionality and they seem to work as expected, but did not test anything else (other than basic + and - expressions).
So i am trying to return the discount amount between 2 .cs files into the main and print out the amount there instead of doing it on the second class. I am pretty new at this and i need help
code is not yet complete
MAIN
using System;
namespace CalcDiscount
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter price");
double input = double.Parse(Console.ReadLine());
Calculator myCalculator = new Calculator();
myCalculator.Calculation(input);
Console.WriteLine("Enter discount");
input = double.Parse(Console.ReadLine());
Console.WriteLine("");
Console.ReadLine();
}
}
}
SECOND FILE
calculator.cs
using System;
namespace CalcDiscount
{
public class Calculator
{
public void Calculation(double input)
{
Console.WriteLine("Your entered the number: " + input);
int i = 1;
if (input != 0)
{
Console.WriteLine(input + " x " + i + " = " + input * i);
}
}
}
}
You could change the method Calculation in your Calculator class, from void to double. The method will calculate the result and return it to the main function, where it will be printed.
Calculation method:
public double Calculation(double input1, double input2)
{
return (input1 * input2);
}
Main:
Console.WriteLine("Enter first input");
double input1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter second input");
double input2 = double.Parse(Console.ReadLine());
Calculator myCalculator = new Calculator();
double result = myCalculator.Calculation(input1, input2);
Console.WriteLine("result = " + result);
public class Calculator
{
public double Calculation(double input)
{
Console.WriteLine("Your entered the number: " + input);
int i = 1;
double result = 0;
if (input != 0)
{
result = i * input;
}
return result;
}
}
I made here a few changes
changed the return type to double (because you send double so it logical to return the same type but not necessary
add a result variable to return the result
did the calculation ( result = i * input)
return the result
note that if i == 0 the result will be 0, because result is initialized to zero, but can apply any logic that you want
and in your Main i read the result from the function and output it to the Console
double result = myCalculator.Calculation(input);
Console.WriteLine("caculcation result is" + result);
I have made bisection method program in C# Console Application. Bisection method works, but for function which is already written in the code. I want to edit program that user can input function which they want to use for bisection method. For example Console.ReadLine() for input "x^2 + x - 2" and then I want it automatically written after return in the code below.
static double Function(double x)
{
return x*x - 2;
} //this is Function which I used in code.
Here is the whole code. (as i mentioned it works for function which is written in static double Function(double x) part
using System;
namespace MPI
{
class MainClass
{
public static void Main(string[] args)
{
// in [a,b]
double inPoc = 0; //a
double inKraj = 0; //b
double sredina = 0;
double tacnost = 0;
Start:
int i = 0; //brojac
Console.Write("Unesite početak intervala: ");
inPoc = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite kraj intervala: ");
inKraj = Convert.ToDouble(Console.ReadLine());
Console.Write("Unesite tacnost: ");
tacnost = Convert.ToDouble(Console.ReadLine());
sredina = (inPoc + inKraj) / 2;
if (Function(inPoc) * Function(inKraj) < 0)
{
while ((Math.Abs(inPoc - inKraj)) > tacnost)
{
sredina = (inPoc + inKraj) / 2;
Console.WriteLine("trenutno X: " + sredina);
Console.WriteLine("Funkcija za trenutno x ima vrednost: " + Function(sredina));
Console.WriteLine("");
i++;
if (Function(sredina) < 0)
{
inPoc = sredina;
}
else
{
inKraj = sredina;
}
}
Console.WriteLine("X: " + sredina);
Console.WriteLine("Broj izvrsenih koraka je " + i);
}
else
{
Console.WriteLine("Krajevi intervala funkcije su istog znaka");
Console.WriteLine();
}
goto Start; //sluzi da vrati program na pocetak kako bi ga opet koristili
}
static double Function(double x)
{
return x*x - 2; //primer funkcije
}
}
}
Looks like this question is asking about the same.
There are two solutions to do this:
Solution 1 - just use Flee.
Copy-paste from documentation:
ExpressionContext context = new ExpressionContext();
VariableCollection variables = context.Variables;
variables.Add("a", 100);
variables.Add("b", 1);
variables.Add("c", 24);
IGenericExpression<bool> e = context.CompileGeneric<bool>("(a = 100 OR b > 0) AND c <> 2");
bool result = e.Evaluate();
So you can do the same, just change input/output types and put your input line into the CompileGeneric
Solution 2 - parse input string manually.
So question can be divided to the two parts:
How to parse input string into the expression tree.
How to execute this tree.
For the first item - please check reverse polish notation. It allows to construct computation stack.
Next you will able to compute your expression tree. Each operand (after trimming) will have variable or integer constant. So just replace variable to the actual value and just parse string to the integer.
I have this question that I have to do for an assignment for school. I am having troubles making it work with decimals. If someone could help me get the program to accept decimals. It will output a decimal but it won't let me input one.
using System;
public class Bank_Account
{
public static void Main()
{
char input, C, D, P, Q;
double balance;
Console.WriteLine("Please enter C for Cheque, D for Deposit, P for Print or Q to quit");
input = Convert.ToChar(Console.ReadLine());
do
{
switch (input)
{
case 'D':
Deposit(ref balance);
break;
case 'P':
Print(balance);
break;
case 'C':
Cheque(ref balance);
break;
default:
Console.WriteLine("{0} is not a valid choice", input);
break;
}
} while (input != 'Q');
}
public static void Deposit(ref double balance)
{
double deposit;
Console.WriteLine("Enter the amount you want to deposit: ");
deposit = Convert.ToInt32(Console.ReadLine());
if (deposit > 1000)
{
deposit = deposit*1.02;
}
else
{
deposit = deposit;
}
balance = +deposit;
}
public static void Cheque(ref double balance)
{
var tempBalance = balance;
double deduction;
const double fee = 1;
do
{
Console.WriteLine("Enter the amount of the cheque: ");
deduction = Convert.ToInt32(Console.ReadLine());
} while (deduction < 0);
tempBalance = balance - deduction - fee;
if (tempBalance < 0)
{
Console.Write("Not enough money in the account");
}
else
{
balance = tempBalance;
}
}
public static void Print(double balance)
{
Console.WriteLine("Your current balance is {0.00}", balance);
}
}
Change this:
deposit = Convert.ToInt32(Console.ReadLine());
to:
deposit = Convert.ToDouble(Console.ReadLine());
since you're not reading an int, but a double. Using TryParse like suggested in another answer would be even better. Also, maybe you should be using decimal and not double if you need exactness, but double if accuracy is less of a concern.
You are converting to Int, change like this,
do
{
Console.WriteLine("Enter the amount of the cheque: ");
deduction = Convert.ToDouble(Console.ReadLine());
}
Try This:
double deposit;
double.TryParse(Console.ReadLine(),out deposit);
deposit = Double.Parse(Console.ReadLine());
I'm pretty new to c# and am confused on how to set the data members and then calculate the tax with a different method. Here is what this part of the program should do:
"If the user selects default the default values you will instantiate a rates object using the default constructor and set the Taxpayer class data member for tax equal to the value returned from calling the rates object CalculateTax method."
-I have a switch statement calling for the default constructor if they choose 'D', I'm not sure how to set the taxpayer class data to default, i'm not sure if the CalculateTax method is correct either.
and then do the same type of thing if they choose 'O'
Here is what I have so far:
using System;
interface Icomparable
{
int CompareTo(Object o);
}
class rates
{
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
private rates()
{
Limit = 30000;
LowRate = 0.15;
HighRate = 0.28;
}
public rates(double Limit; double LowRate; double HighRate;)
{
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
}
public CalculateTax()
{
if(Income < Limit)
{TaxOwed = (Income * LowRate)}
else
{TaxOwed = (Income * HighRate)}
}
}
public class taxpayer : IComparable
{
public string SSN{get; set;}
public double Income{get; set;}
public double TaxOwed{get;}
int IComparable.CompareTo(Object o)
{
int returnVal;
taxpayer temp = (taxpayer)o;
if(this.TaxOwed > temp.TaxOwed)
returnVal = 1;
else
if(this.TaxOwed < temp.TaxOwed)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
public getRates()
{
double Limit;
double LowRate;
double HighRate;
Console.WriteLine("Do you want default values(enter D) or enter your own (enter O)?");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case'D':
rates();
break;
case'O':
rates(double Limit; double LowRate; double HighRate;)
break;
default:
Console.WriteLine("Invalid input");
goto getRates();
}
}
}
Any help with this would be very much appreciated.
I don't see why you would keep re creating an object that you have all the values for.
Here is an alternate pattern, static presets + factory
class Rates
{
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
static readonly Rates default = new Rates(30000,0.15,0.28);
static readonly Rates govna = new Rates(300000,0.1,0.2);
static readonly Rates priest = new Rates(300,0.05,0.07);
public static Rates createRates()
{
double Limit; double LowRate; double HighRate;
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
return new Rates( Limit, LowRate, HighRate );
}
private Rates(double limit; double lowRate; double highRate;)
{
Limit = limit;
LowRate = lowRate;
HighRate = highRate;
}
public double CalculateTax( double Income)
{
if(Income < Limit)
{return (Income * LowRate)}
else
{return (Income * HighRate)}
}
}
Oh and whats with goto?
while( null == ratesResult ){
Console.WriteLine("Do you want default values(enter D) or enter your own (enter O)?");
entry = Convert.ToChar(Console.ReadLine());
switch (entry) //set switch
{
case'D':
ratesResult = Rates.default;
break;
case'O':
ratesResult = Rates.createRates();
break;
default:
Console.WriteLine("Invalid input");
}
}
You have many problems with your code, buddy. Here is some advice that might guide you in the right direction.
In the following properties, you should also have a set; accessor to be able to store those values.
public double Limit{get;}
public double LowRate{get;}
public double HighRate{get;}
In the following function, do you want to prompt the user to enter values? If so, change the first line from
public rates(double Limit; double LowRate; double HighRate;)
to
public rates(bool dummy)
Now your code will look like
public rates(bool dummy) //Note that dummy is not used in this function. It just distinguishes rates() from rates(bool)
{
Console.Write("Enter dollar limit: ");
Limit = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the low rate: ");
LowRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the high rate: ");
HighRate = Convert.ToDouble(Console.ReadLine());
}
the dummy is just to allow the the code to distinguish your two different functions.
In your switch statement, just call the rates(bool dummy) function instead of the other one. For the dummy, assign it either true or false, who cares.... It'd look like the following.
switch (entry) //set switch
{
case'D':
rates();
break;
case'O':
rates(true)
break;
default:
Console.WriteLine("Invalid input");
goto getRates();
}
There's more problems with your code, but you have to revise it before we can help you further. You should actually try to use it in VS, since the editor can help you fix problems by giving you specific errors.