C# don't understand calling methods. object oriented programming - c#

I've just started object oriented programming and I don't quite understand how to call another method. I wanted to calculate the percentage increase and then put out the resulting overall price. This would be done by calling the method to do the working out then returning the value to the other method. However I'm unsure about how to cross over between methods.
Could someone please explain how I'm meant to do this? Preferably not just giving the answer so I can fully understand what's happening.
p.s. this piece of code is in a class called RetailPricing. As I've copied and pasted it, it doesn't look like it's all formatted properly (I understand how to call this class to the main program)
namespace week7exercise2
{
class RetailPricing
{
public void CalculateRetailPrice()
{
double inputcost;
double inputpercent;
string inputitemcost;
string inputmarkup;
Console.Write("Please Input The Cost Of The Item: ");
inputitemcost = Console.ReadLine();
inputcost = double.Parse(inputitemcost);
Console.Write("Please Input The Markup Percentage: ");
inputmarkup = Console.ReadLine();
inputpercent = double.Parse(inputmarkup);
Console.Write("Your Retail Price Is: " + newprice);
}
public double sum(double MarkUpPercentage, double overallprice, double newprice)
{
MarkUpPercentage = inputpercent + 100;
overallprice = MarkUpPercentage / 100;
newprice = inputcost * overallprice;
return newprice;
}
}
}

What I understood is that you want to call a function to perform some calculations.
Before your last line:
Console.Write("Your Retail Price Is: " + newprice);
What you need to do is call your function for calculating price and it'll return the price after calculating it. So simply do:
double newprice = sum(inputpercent,inputcost)
And change your sum function to:
public double sum(double MarkUpPercentage, double overallprice)
{
MarkUpPercentage = inputpercent + 100;
overallprice = MarkUpPercentage / 100;
double newprice = inputcost * overallprice;
return newprice;
}

Related

User Input Validation

I am creating a simple income tax calculator and would like too add some user input validations. Currently I am experimenting with a TryParse method. I would like my program to check each input for the specific input types and if an invalid input is entered, the program will first notify the user then ask them to try again.
My current attempt successfully detects whether or not the input types are correct, but I am unsure on how I can redirect the user to retry. Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IncomeTaxCalculator
{
class IncomeTaxV2
{
public static void Main()
{
// Define variables
const double incomeTax = 0.02, deduction = 10000; // Constant values - These never change
int children; // Amount of children
double Taxdue, totalIncomeTax; // Decimal valued variables
// Ask total income
Console.Write("What is your total income: ");
bool succeed = double.TryParse(Console.ReadLine(), out totalIncomeTax);
// Ask amount of children
Console.Write("How many children do you have: ");
bool succeeded = int.TryParse(Console.ReadLine(), out children);
// If statement to check input validation.
if (succeed && succeeded)
{
// User input validation
// Calculate Deductions
int childTax = children * 2000; // total amount for each child
double total_deductions = (double)deduction + childTax; // total deductions = 10k + childtax
// Calculate User input tax takeaway (-) the total amount of deductions (Equation above)
double taxDueCalc = totalIncomeTax - total_deductions;
// Find 2% of the Result for the amount of Tax due
Taxdue = taxDueCalc * incomeTax;
// Print result
Console.Write("You owe a total of $" + Taxdue + " tax.");
} else
{
// Notify user of error
Console.Write("You must enter a valid number.");
// Redirect too first set of TryParse statements
}
// End program
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
}
}
Redirect must go into else statement. After researching potential methods it seems I might have too learn too use functions and pass information through parameters.
An easy approach is to use a loop, and signal the end when user entry has completed:
bool entryCompleted = false;
while (!entryCompleted)
{
if (succeed && succeeded)
{
// ..
entryCompleted = true;
}
}
I will use the recursive function for this question.
public static void Main()
{
incomeTax();
// End program
Console.WriteLine("\n\n Hit Enter to exit.");
Console.ReadLine();
}
public void incomeTax()
{
// Define variables
const double incomeTax = 0.02, deduction = 10000; // Constant values - These never change
int children; // Amount of children
double Taxdue, totalIncomeTax; // Decimal valued variables
// Ask total income
Console.Write("What is your total income: ");
bool succeed = double.TryParse(Console.ReadLine(), out totalIncomeTax);
// Ask amount of children
Console.Write("How many children do you have: ");
bool succeeded = int.TryParse(Console.ReadLine(), out children);
// If statement to check input validation.
if (succeed && succeeded)
{
// User input validation
// Calculate Deductions
int childTax = children * 2000; // total amount for each child
double total_deductions = (double)deduction + childTax; // total deductions = 10k + childtax
// Calculate User input tax takeaway (-) the total amount of deductions (Equation above)
double taxDueCalc = totalIncomeTax - total_deductions;
// Find 2% of the Result for the amount of Tax due
Taxdue = taxDueCalc * incomeTax;
// Print result
Console.Write("You owe a total of $" + Taxdue + " tax.");
} else {
// Notify user of error
Console.Write("You must enter a valid number.");
// Redirect too first set of TryParse statements
incomeTax();
}
}
When the input number is invalid, it will call back the same function. This happens until the program enters if statement.

C# - Stuck with use of list and array

I have been practicing c# nowadays and decided to write a code that converts any decimal to any base representation for practice purpose. And i have some troubles. Since i want to practice i decided to do it with an additional function where calculations take place. First i wanted to use an array to keep my result. But since ,at the beginning, i do not know the length of the array i could not define it.So i decided to use list(somehow i assumed undeclared slots are 0 as default). This is what i end up with.
class MainClass
{
static double number;
static double baseToConvert;
static int counter = 0;
static List<double> converted = new List<double>();
public static void Main(string[] args)
{
Console.WriteLine("Enter a decimal");
number = double.Parse(Console.ReadLine());
Console.WriteLine("Enter a base you want to convert to");
baseToConvert = double.Parse(Console.ReadLine());
ConverterToBase(number);
for (int i = converted.Count - 1; i >= 0; i--)
{
Console.WriteLine(converted[i]);
}
Console.ReadLine();
}
public static void ConverterToBase(double x)
{
double temp = x;
while (x >= baseToConvert)
{
x /= baseToConvert;
counter++;
}
converted[counter] = x;
counter = 0;
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
else
{
converted[0] = temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter));
}
}
}
But after i write inputs console gets stuck without an error. My guess is that since i do not have any elements in the list " converted[counter] " does not make sense. But i do not know maybe the problem is somewhere else.
My question is not about the way i calculate the problem(Of course any suggestions are welcomed). I just want to know what i am doing wrong and how i can handle such situation(unknown array size , use of list , accessing a variable,array,.. etc from another method... ).
Thanks.
My previous answer was wrong as pointed out by #Rufus L. There is no infinite for loop. However upon further review, there seems to be an infinite recursion going on in your code in this line:
if (temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)) >= baseToConvert)
{
ConverterToBase(temp - x * Math.Pow(baseToConvert, Convert.ToDouble(counter)));
}
ConverterToBase calls itself and there seems to be no base case nor return statement to end the recursion.
In the method named "ConverterToBase(double x)" you want to set value of 0 element. But you didn't add any element. The converted is Empty.
Firstly add value or values to your list.

How to get max value of List<> in double datatype

I am trying to get Max value from List<>, but it's returning rounded value to integer. Is there some special way how to proceed this?
private List<double> dataX = new List<double>();
double maxVal = dataX.Max<double>();
Debug.WriteLine("max: " + maxVal);
Edit:
As requested here is feeding data:
for (int i = 0; i < 10; i++)
{
data.Add(new ChartData(i, rand.NextDouble() * 10));
Debug.WriteLine(data.Last<ChartData>().Y);
}
My debug window shows this:
5,9358753151893
7,87125875608588
3,77212246589927
9,36056426230844
2,27154730924943
9,80201833872218
5,7350595275569
3,04650606729393
5,81677517658881
0,0514464220271662
max: 8
So I don't think the feeding side is wrong. And for whole picture, here you can see ChartData type:
public class ChartData
{
public double X { get; set; }
public double Y { get; set; }
public ChartData(double X, double Y)
{
this.X = X;
this.Y = Y;
}
}
And how I'm getting simple List from my ChartData class:
private List<ChartData> data = new List<ChartData>();
private List<double> dataX = new List<double>();
void updateMaxMin()
{
dataX.Clear();
dataY.Clear();
for (int i = 0; i < data.Count - 1; i++)
{
dataX.Add(data[i].X);
dataY.Add(data[i].Y);
}
}
There are two likely scenarios here.
You are rounding the values as you enter them into the list (as #sam mentioned in his comment).
You are expecting a double value ending in 0 to show these decimal places. A double will always drop off the insignificant digits. So for example, 1.500 will be truncated to 1.5. This is how doubles were intended to work. Another article that briefly talks about this is Double Skips last decimal if zero. If you are looking for a different Visual output, I would recommend converting the result to a string and then using string formatting. An example would be the following (using 2 decimal places):
Console.WriteLine(string.Format("max: {0:0.00}", maxVal));
Most likely the problem is in the way you insert into the list as some had suggested in here (you mentioned about rounded to an integer, so I'm assuming it is probably not visual display related).
Try debug your data in the list:
private List<double> dataX = new List<double>();
...
foreach(var data in dataX)
{
Debug.WriteLine("data: " + data);
}
double maxVal = dataX.Max<double>();
Debug.WriteLine("max: " + maxVal);
A possible issue with the way you populate the list could be something like:
var myNum = new[] { 1, 2, 3, 4, 5, 6 };
foreach (var num in myNum)
{
dataX.Add(num / 2);
}
The data that was added into the dataX is actually an integer (as the division by 2 returns an integer).
double doesn't keep insignificant digits. - there's no difference between 9 and 9.0 and 9.0000
If you want just display purpose use refer this link C# Double - ToString() formatting with two decimal places but no rounding for convert the double to string with decimal places. but,if you using calculation it's no need for keeping with decimal places.
Ok I found mistake. I have been calculating max value from different array. So i got correct max value anyway. There should be:
double maxVal = dataY.Max<double>();
instead of
double maxVal = dataX.Max<double>();
So I guess, this isn't much helping, so I will delete this question after you realized I did basic fault.
Thank you all anyway.

simple procedural maths program in C#

so I am creating a very simple program in C# (my first one).
It should do an average of X numbers.. instead of writing it all out manually, it'll be much better done procedurally (I'm not sure if that's even a word). Basically as I've done with the 'amount' in the example below. I could just divide it by 2 (in this case). But instead I have a variable that increases with each new entry - so the program would work regardless of how many entries there are.
The same thing I'd need to do with the variables 'first', 'second' etc. I need some variable that would change dynamically, based on the number of entries. This should be a peace of cake algorithm-wise but this is my first day with C# and I can't manage to do it (namely because I am lacking the knowledge of syntax).
double first;
double second;
int amount = 0;
double result;
Console.Write("Write your first number");
first = int.Parse(Console.ReadLine());
++amount;
Console.Write("Write your second number");
second = int.Parse(Console.ReadLine());
++amount;
result = (first + second) / amount;
Console.Write("The average of your numbers is: " + result);
Thanks
Here's the gist of what I think you want. I'll use pseudocode to give you the opportunity to learn the C#:
create a list of numbers
output prompt
read input line
while the input line had a value
parse the input value
add the parsed value to the list of numbers
output prompt
read input line
calculate the sum of the values divided by the length of the list
output the calculated average
I think you're after the recusive average?
class Program
{
static void Main(string[] args)
{
//Compute Average Recursively:
int average_count = 0;
double average = 0;
average = RecursiveAverage(average, ref average_count, 1);
average = RecursiveAverage(average, ref average_count, 2);
average = RecursiveAverage(average, ref average_count, 3);
average = RecursiveAverage(average, ref average_count, 4);
Console.WriteLine(average); //2.5
}
private static double RecursiveAverage(double previous, ref int average_count, double next)
{
average_count += 1;
return ((average_count - 1.0) / (average_count)) * previous + (1.0 / (average_count)) * next;
}
}
See: http://people.revoledu.com/kardi/tutorial/RecursiveStatistic/Time-Average.htm
Update: Keep updating the average indefinitely (or until average_count gets too large to store without a BigInteger ) without having to remember all the numbers...
while (true)
{
var next = int.Parse(Console.ReadLine());
average = RecursiveAverage(average, ref average_count, next);
Console.WriteLine("Average is now: " + average);
}

Calculating the area

using System;
namespace area
{
class Program
{
static void Main(string[] args)
{
double basse;
double height;
Console.WriteLine("Enter your base length: ");
basse = Convert.ToDouble(Console.ReadLine());
Console.WriteLine( "Enter the height: ");
height = Convert.ToDouble(Console.ReadLine());
double area = Program.triangleArea(basse, height);
Console.WriteLine("Your area is {0:f3}", area);
Console.ReadLine();
double pryrmid = Program.pyramidVolume( triangleArea);
Console.WriteLine(" Pyramid Volume is {0:f3}" , pryrmid);
}
public static double triangleArea(double basse, double height)
{
return (0.5 * basse) * height;
}
public static double pyramidVolume (double triangleArea)
{
return (1/3) * triangleArea;
}
}
}
I'm trying the calculate the volume of a pryamid using the methods ive defined.
I keep getting the error
Argument '1': cannot convert from 'method group' to 'double' (CS1503)
- \vmware-host\Shared Folders\Documents\SharpDevelop Projects\WS_6_D\WS_6_D\Program.cs:28,57
and
The best overloaded method match for
'area.Program.pyramidVolume(double)' has some invalid arguments
(CS1502) - \vmware-host\Shared Folders\Documents\SharpDevelop
Projects\WS_6_D\WS_6_D\Program.cs:28,34
I was wondering if someone could help me get on the right track.
The problem is that triangleArea in
double pryrmid = Program.pyramidVolume( triangleArea); is not a variable, hence it points to the static method.
Try double pryrmid = Program.pyramidVolume( area); instead.
The compiler is expecting something it can evaluate to a double, but you supply the name of a function (triangleArea).
Instead, you probably want to pass the area you calculated previously.
I think you meant to say
double pryrmid = Program.pyramidVolume(area);
instead of
double pryrmid = Program.pyramidVolume( triangleArea);
triangleArea is your method, you used area as your result value.

Categories

Resources