I would like to make a program that calculates circumference. Though, would much rather have a rounded answer (two decimal places) as a pose to seven decimal places. But when I use the Math.Round method, it doesn't seem to round. What am I doing wrong?
Console.Write("Circumference Calculator! Enter the radius of the circle: ");
int inputRadius = Convert.ToInt32(Console.ReadLine());
double ans = Math.Sqrt(inputRadius) * Math.PI;
Math.Round(ans, 2);
Console.WriteLine("Your answer is: " + ans + " squared.");
Math.Round does not modify provided argument - it returns a new value. So you have to assigned it back to a variable to make it work:
ans = Math.Round(ans, 2);
You have to use the return value of Math.Round, it doesn't take the variable by reference.
//Greet user & give instructions
#region
Console.WriteLine("Circumference Calculator");
Console.WriteLine("");
Console.Write("Welcome to the Circumference Calculator! Please enter the radius of the circle: ");
#endregion
//Get input from user and calculate answer
#region
Console.ForegroundColor = oldColour;
int inputRadius = Convert.ToInt32(Console.ReadLine());
double ans = Math.Sqrt(inputRadius) * Math.PI;
Console.ForegroundColor = ConsoleColor.DarkYellow;
double roundedAnswer = Math.Round(ans, 2);
Console.WriteLine("Your answer is: " + roundedAnswer + " squared.");
#endregion
Related
I'm trying to create a map-related calculator and I'm having a problem with the Math.Round method. Basically, I want the program to take the real-life length and the length on a map to calculate the scale of said map. After it calculates the scale it should round it from a double to an int.
So for example the real-life length is 3000000 cm and the on map length equals 8,5 cm now after dividing these we get 352 941,176 that's our scalenoteven in this context. Now after rounding it, the scale should be 1:352 941 but instead the program gives me a scale of 1:352.
double Scalenoteven;
int Scaleeven;
//RealLengthincm and Maplength are taken from the user
Scalenoteven = RealLengthincm / MapLength;
Scaleeven = (int)Math.Round(Scalenoteven, 1, MidpointRounding.ToEven);
So with the added culture info and RealLengthincm = RealLength * 100; this should be working.
using System.Globalization;
double RealLength;
string RealLengthString;
double MapLength;
string MapLengthString;
double RealLengthincm;
double Scalenoteven;
int Scaleeven;
Console.WriteLine("Firstly will the real length be in meters or kilometers?");
string Answer;
Answer = Console.ReadLine();
if (Answer == "meters")
{
Console.WriteLine("Alright!");
Console.WriteLine("So what's the real length?");
var culture = new CultureInfo("de-DE");
RealLengthString = Console.ReadLine(); // assuming 30000
RealLength = double.Parse(RealLengthString, culture);
RealLengthincm = RealLength * 100;
Console.WriteLine("now what's the length on the map in cm");
MapLengthString = Console.ReadLine(); // assuming 8,5
MapLength = double.Parse(MapLengthString, culture);
//RealLengthincm and Maplength are taken from the user
Scalenoteven = RealLengthincm / MapLength;
Scaleeven = (int)Math.Round(Scalenoteven, 0, MidpointRounding.ToZero);
Console.WriteLine("The Scale is 1:" + Scaleeven); // outputs 1:352941
}
public static void Main()
{
WriteLine("Farenheit Here>>");
int F = Int32.Parse(ReadLine());
Double FtoC = (5.0 / 9.0) * (F - 32);
WriteLine("the celsius is {0} ", FtoC);
}
The input works for whole numbers but I also want it to work for Decimal numbers. Ex. If I were to type in 10 it will give me an answer, but if I were to type in 10.5 it will stop working. I am indeed new to C#.
you need to use the number parser you want, currently you are using int
Int32.Parse(ReadLine());
You can use double, or decimal (I'd suggest using decimal over double)
decimal F = Decimal.Parse(ReadLine());
then change to
decimal FtoC = (5.0M / 9.0M) * (F - 32M);
WriteLine("the celsius is {0} ", FtoC)
(the M is used to define decimal literals)
int does not store decimal number. Use double or decimal
public static void Main()
{
WriteLine("Farenheit Here>>");
double F = double.Parse(ReadLine());
Double FtoC = (5.0 / 9.0) * (F - 32);
WriteLine("the celsius is {0} ", FtoC);
}
Well, Int32 is specifically for handling integers. If you want to handle Decimal values, they have their own Parse method so I'd be looking at something like:
public static void Main() {
Console.Write("Farenheit Here>> ");
Decimal F = Decimal.Parse(Console.ReadLine());
Decimal FtoC = (5.0M / 9.0M) * (F - 32M);
Console.WriteLine("The celsius is {0} ", FtoC);
}
And note the use of the M suffix. If you want to use Decimal types, you're probably better off committing fully to them, rather than reverting to the double type with all its foibles.
static void Main(string[] args)
{
int choice;
choice = 0;
double length;
length = 0.00;
double height;
height = 0.00; //initiating variables
double base1;
base1 = 0.00;
double width;
width = 0.00;
double radius;
radius = 0.00;
double total;
total = 0.00;
Console.WriteLine("What shape would you like to make?");
Console.WriteLine("Please select one option (1, 2, 3, or 4)");
Console.WriteLine("1. Square.");
Console.WriteLine("2. Triangle."); //menu on the console
Console.WriteLine("3. Rectangle.");
Console.WriteLine("4. Circle.");
choice = int.Parse(Console.ReadLine());
if (choice == 1)
{
Console.WriteLine("Great! You chose Square.");
Console.WriteLine("Let's help you calculate the area of a square.");
Console.WriteLine("But first, we need to know the length of this square");
Console.WriteLine("Enter the length(Integer, or Decimal value is just fine:");
length = double.Parse(Console.ReadLine());
}
else if (choice == 2)
{
Console.WriteLine("Great! You chose Triangle.");
Console.WriteLine("Let's help you calculate the area of a triangle.");
Console.WriteLine("But first, we need to know the base and height of this triangle.");
Console.WriteLine("Enter the base(Integer, or Decimal value is just fine):");
base1 = double.Parse(Console.ReadLine()); //writing to the console depending on what choice
Console.WriteLine("Enter the height(Integer, or Decimal value is just fine):");
height = double.Parse(Console.ReadLine());
}
else if (choice == 3)
{
Console.WriteLine("Great! You chose Rectangle.");
Console.WriteLine("Let's help you calculate the area of a rectangle.");
Console.WriteLine("But first, we need to know the width and height of this rectangle.");
Console.WriteLine("Enter the width(Integer, or Decimal value is just fine):");
width = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the height(Integer, or Decimal value is just fine):");
height = double.Parse(Console.ReadLine());
}
else if (choice == 4)
{
Console.WriteLine("Great! You chose Circle.");
Console.WriteLine("Let's help you calculate the area of a circle.");
Console.WriteLine("But first, we need to know the radius of this circle.");
Console.WriteLine("Enter the radius(Integer, or Decimal value is just fine:");
radius = double.Parse(Console.ReadLine());
}
Main_Calculations(args, total, base1, height, width, choice); //Sending Paramters to the next method
}
static void Main_Calculations(string[] args, double base1, double height, double width, double total, int choice) //bringing in parameters
{
if(choice == 2)
{
total = (base1 * height) * 0.5; //Calculations for triangle
Console.WriteLine("The area of a triangle is: " + total);
}
else if(choice == 3)
{
total = width * height; //calculations for rectangle
Console.WriteLine("The area of a rectangle is: " + total);
}
Main_Calculations(choice, total); //Sending Paramters to the next method
}
static void Main_Calculations(double length, double radius, double total, double choice)
{
if(choice == 1)
{
total = length * length; //Calculations for square
Console.WriteLine("The area of a square is: " + total);
}
else if(choice == 4)
{
total = (radius * radius) * 3.14; //calculations for circle
Console.WriteLine("The area of a circle is " + total); //prints the answer to the console
}
}
}
}
My 2nd sender for (Math_Calculations) is giving me an error for no overload takes 2 arguments, I don't understand why it won't work the way I have it. Seems possibly I am just missing one phrase, I have stepped in and out of the code looking to now avail.
When you call the 2nd method Math_Calculations, you only give 2 arguments to the method when you ask in the method for 4 arguments
So, What you need to do is or, you give 2 arguments extra to the 2dn Math_Calculations call, OR you remove 2 arguments from the method.
This would be easier to answer with line numbers, but you call
Main_Calculations(choice,total);
when there is no method for Main_Calculations that takes two arguments.Just as Habib has pointed out.
I am having trouble with my bmi calculator.
Here are the details:
Write a program that takes a person's height and
weight in pounds and returns the body mass index(BMI).
BMI is defined as the weight, expressed in kilograms, *divided by the square of the height expressed in meters.*
One inch is 0.0254 meters and one pound is
0.454 kilograms.
This is a windows form app btw.
Well when I am trying to square the height using ^, it gives me an error: Operator '^'...
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
//Declare variables.
decimal heightDecimal ;
decimal weightDecimal;
decimal bmiDecimal;
decimal resultDecimal;
//Get user input.
heightDecimal = Decimal.Parse(txtHeight.Text);
weightDecimal = Decimal.Parse(txtWeight.Text);
//Calculations.
weightDecimal = (Decimal)0.454;
heightDecimal = (Decimal)0.0254;
bmiDecimal = weightDecimal / heightDecimal ^ 2;
//Display.
lblBMI.Text = bmiDecimal.ToString();
}
I am trying to figure out the calculations. I am confused. Can anyone please help me? Thanks.
Tested what everyone said. I got some weird numbers. I started it and I put 5 for my height and 100 for my weight(random) and I got 700? Are my calculations wrong?
bmiDecimal = weightDecimal / heightDecimal ^ 2;
You probably meant
bmiDecimal = weightDecimal / (heightDecimal * heightDecimal);
^ is the XOR operator in C#.
Edit:
If you don't use metric unit, you have to multiply the results by 703.06957964, see Wikipedia.
bmiDecimal = weightDecimal / (heightDecimal * heightDecimal);
Try the above. ^ is xor
Alternatively
bmiDecimal = weightDecimal / Math.Pow(heightDecimal, 2)
Some test values could be 90 kg and 1.80 m
90 / (1.80 * 1.80)
90 kg is roughly 200 lbs and 1.80 m is 5.11 if you're not used to the metric system
Here's what it would look like in a Console App:
decimal feetDecimal;
decimal inchesDecimal;
decimal weightDecimal;
decimal bmiDecimal;
decimal resultDecimal;
//Get user input.
Console.WriteLine("Enter feet:");
feetDecimal = Decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter inches:");
inchesDecimal = Decimal.Parse(Console.ReadLine());
Console.WriteLine("Enter weight in pounds:");
weightDecimal = Decimal.Parse(Console.ReadLine());
//Calculations.
inchesDecimal += feetDecimal * 12;
decimal height = inchesDecimal * (decimal)0.0254;
decimal weight = weightDecimal * (decimal)0.453592;
bmiDecimal = weight / (height * height);
//Display.
Console.WriteLine(bmiDecimal.ToString());
Console.ReadLine();
The .NET Framework also provides a Math class that has a Pow method, which allows for squaring of numbers like this:
Math.Pow(2, 2)
That is 2 squared, which equals 4.
Your code would be:
bmiDecimal = weightDecimal / Math.Pow(heightDecimal, 2);
Note: For more information read documentation for Math.Pow.
Weight = Convert.ToDecimal(txtWeight.Text);
Height = Convert.ToDecimal(txtHeight.Text);
BodyMassIndex = (Weight * 703) / (Height * Height);
txtMassIndex.Text = Convert.ToString(Math.Round(BodyMassIndex, 4) + " lbs/ Inch Square");
I don't understand if the calculation for netPay = grossPay - (fedtax withholding + social security tax withholding). Are my calculations correct within the program? Dealing with such in editedTax?? If someone could help I'd appreciate it.
More info: When I display netPay within an output, I receive a runtime error, where I couldn't convert the negative to currency with {0:c2}.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
string empName;
string userInput;
double netPay;
double editedTax1;
double grossPay;
double editedTax2;
double hrsWorked;
double ovtWorked;
double payRate;
const double FED_TAX = .28;
const double SS_TAX = 7.65;
// step 1
Console.WriteLine(" WEEKLY PAYROLL INFORMATION");
// step 2
Console.WriteLine(" --------------------------");
// step 3
Console.Write("\n Please enter the employer's name: ");
empName = Console.ReadLine();
//step 4
Console.Write("\n Please enter the number of hours worked this week: ");
userInput = Console.ReadLine();
hrsWorked = Convert.ToDouble(userInput);
// step 5
Console.Write("\n Please enter the number of OVERTIME HOURS worked this week: ");
userInput = Console.ReadLine();
ovtWorked = Convert.ToInt32(userInput);
// step 6
Console.Write("\n Please enter employee's HOURLY PAY RATE: ");
userInput = Console.ReadLine();
payRate = Convert.ToDouble(userInput);
// step 7
grossPay = (hrsWorked * payRate + ovtWorked * 1.5 * payRate);
// step 8
editedTax1 = FED_TAX * grossPay;
// step 9
editedTax2 = SS_TAX * grossPay;
// step 10
netPay = editedTax1 + editedTax2 - grossPay;
// step 11
Console.WriteLine("\n\n The weekly payroll information summary for: " + empName);
Console.WriteLine("\n Gross pay: {0:C2} ", grossPay);
// step 12
Console.WriteLine(" Federal income taxes witheld: {0:C2} ", editedTax1);
Console.WriteLine(" Social Security taxes witheld: {0:C2} ", editedTax2);
Console.WriteLine(" Net Pay: {0:C2}", netPay);
}
}
}
netPay is assigned the opposite value in the code as compared to your description below.
I don't see any syntax errors or anything.
What is the problem you're having? What are some of the things you've tried?
The reason you're getting a negative number in the calculation is because your SS_TAX is 7.65. I think the number you want is 0.0765.
I'm not sure exactly what you're asking for, but simple substitution in the assignment statements yields the following formulas:
Since
editedTax1 = FED_TAX * grossPay;
editedTax2 = SS_TAX * grossPay;
netPay = editedTax1 + editedTax2 - grossPay;
then
netPay = FED_TAX * grossPay + SS_TAX * grossPay - grossPay;
meaning
netPay = grossPay * (FED_TAX + SS_TAX - 1);
so something seems a little off here...
Are you sure you don't want
netPay = grossPay - (editedTax1 + editedTax2);
instead of
netPay = editedTax1 + editedTax2 - grossPay;
This seems to match what you're looking for as
netPay = grossPay - (FED_TAX * grossPay + SS_TAX * grossPay);
or
netPay = grossPay * (1 - (FED_TAX + SS_TAX));
...unless I'm missing something, of course.
Edit: I was missing something. Your tax constants are a percent, but you're not dividing by 100 when you do calculations with them. You have two options:
Divide by 100 when you use the values in a calculation, like:
editedTax1 = (FED_TAX / 100) * grossPay;
Store the constants as the decimal representation, not a percent, like:
const double FED_TAX = .0028;
I have tested this code on my machine and it works correctly:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
const double FEDERAL_TAX_RATE= 0.28;
const double SOCIAL_SECURITY_RATE = 0.0765; // I am assuming the 7.65 was supposed to be 7.65%... therefore it should be 0.0765
Console.WriteLine(" WEEKLY PAYROLL INFORMATION");
Console.WriteLine(" --------------------------");
Console.Write("\n Please enter the employer's name: ");
string empName = Console.ReadLine();
Console.Write("\n Please enter the number of hours worked this week: ");
double hrsWorked = Convert.ToDouble(Console.ReadLine());
Console.Write("\n Please enter the number of OVERTIME HOURS worked this week: ");
double ovtWorked = Convert.ToInt32(Console.ReadLine());
Console.Write("\n Please enter employee's HOURLY PAY RATE: ");
double payRate = Convert.ToDouble(Console.ReadLine());
double grossPay = CalculateGrossPay(hrsWorked, payRate, ovtWorked);
double federalTaxWithheld = CalculateTax(grossPay, FEDERAL_TAX_RATE);
double socialSecurityWithheld = CalculateTax(grossPay, SOCIAL_SECURITY_RATE);
double netPay = CalculateNetPay(grossPay, federalTaxWithheld + socialSecurityWithheld);
Console.WriteLine("\n\n The weekly payroll information summary for: " + empName);
Console.WriteLine("\n Gross pay: {0:C2} ", grossPay);
Console.WriteLine(" Federal income taxes witheld: {0:C2} ", federalTaxWithheld);
Console.WriteLine(" Social Security taxes witheld: {0:C2} ", socialSecurityWithheld);
Console.WriteLine(" Net Pay: {0:C2}", netPay);
Console.ReadLine(); // You don't need this line if your running from the command line to begin with
}
static double CalculateGrossPay(double HoursWorked, double PayRate, double OvertimeHoursWorked)
{
return PayRate * (HoursWorked + 1.5 * OvertimeHoursWorked);
}
static double CalculateTax(double GrossPay, double TaxRate)
{
return GrossPay * TaxRate;
}
static double CalculateNetPay(double GrossPay, double TaxAmount)
{
return GrossPay - TaxAmount;
}
}
}
Since it looks as though this is your first programming course, I'll offer you some pointers that they probably will not emphasize in your class:
Use descriptive variable names. If you notice yourself putting a number after your variable name, it can probably done a different and more readable way!
Utilize functions, they bundle common tasks in one section of code and increase readability significantly.
You may want to add some exception handling or validation to this code. For example, what if you accidentally passed -1 into OverTimeHours?
I understand this might not matter at this point in your programming journey, but it's always good to start off using coding techniques that make your code more readable and less confusing, especially for people who may have to maintain it in the future.