Having incorrect solutions when program executes, - c#

I've been working on a two class BMI Calculator for my class. I finally have managed to debug on get the program to execute. However I noticed that it wont let me enter height or weight as a decimal.
Example
putting 6.4 for height causes it to crash
Putting 6 height and 220 weight always seems to declare underweight and show incorrect bmi reading
example:
Height 6
Weight 220
BMI: score $0.09
It's calculating the BMI wrong. Looking at the code I can't seem to identify why its calculating this wrong.
-Edit- Managed to get it to take decimals! (Thank you everyone!) However it still seems to be messing up calculating the BMI
-Edit- Code Works!
(Code Part 1) Updated Mk2
using System;
namespace Calculator
{
public class BMICalc
{
private const
decimal REQ = 703;
private decimal weightPerson;
private decimal heightPerson;
public BMICalc()
{
}
public BMICalc(decimal weiP, decimal heiP)
{
this.weightPerson = weiP;
this.heightPerson = heiP;
}
public decimal SetBmi()
{
decimal bmi;
bmi = Convert.ToDecimal((this.weightPerson * 0.45m) / ((this.heightPerson * 12 * 0.025m) * (this.heightPerson * 12 * 0.025m)));
if (bmi < 18.5m)
{
Console.WriteLine("UnderWeight");
Console.ReadLine();
}
if (bmi > 18.5m && bmi < 25.0m)
{
Console.WriteLine("Normal");
Console.ReadLine();
}
if (bmi > 25.0m && bmi < 29.9m)
{
Console.WriteLine("OverWeight");
Console.ReadLine();
}
if (bmi > 29.9m && bmi < 40.0m)
{
Console.WriteLine("Obese");
Console.ReadLine();
}
return bmi;
}
public override string ToString()
{
return "\tCalculator" +
"\n\n Weight:" + this.weightPerson +
"\n\n Height:" + this.heightPerson +
"\n\n BMI Score:" + SetBmi().ToString();
}
}
}
Code (Part 2) Updated Mk 2
namespace Calculator
{
public class App
{
public static void Main() //
{
decimal heiP, weiP;
heiP = InputHeight();
weiP = InputWeight();
BMICalc bmiCal = new BMICalc(weiP, heiP);
Console.Clear();
Console.WriteLine(bmiCal.ToString());
Console.ReadKey();
}
public static decimal InputHeight()
{
decimal hNumber;
Console.Write("Please enter your height: ");
hNumber = Convert.ToDecimal(Console.ReadLine());
return hNumber;
}
public static decimal InputWeight()
{
Decimal wNumber;
Console.Write("Please enter your weight: ");
wNumber = Convert.ToDecimal(Console.ReadLine());
return wNumber;
}
}
}

You're input parameters into the constructor expects weight (weiP), height (heiP) (in that order) while you're passing height, weight from BMICalc bmiCal = new BMICalc(heiP, weiP);
That's the reason the value being output is incorrect. Interchange the parameters and it should be fine.
EDIT
Since you're entering the weight in Lbs and height in feet, you would need to convert feet into inches ( multiplying by 12) and then also multiplying the height and weight by the conversion metric.
So the formula would be:
bmi = Convert.ToDecimal((this.weightPerson * 0.45) / ((this.heightPerson * 12 * 0.025) * (this.heightPerson * 12 * 0.025)));
The currency comes in when it uses the ToString() overridden method. The format specified there is for currency.

Related

I am not able to convert final answer into decimal form

I am not able to bring my final output in decimal terms
When i tried to convert double to decimal it gives error
using System;
namespace Recurring_Deposit_Calc
{
class Program
{
private double _amount, _month,_a;
private double _b,_simpleintrest,_matureAmount,_x;
public void Calulate() {
Console.WriteLine("Intrest Rate :6.8%");
Console.WriteLine("Enter amount you deposit per month:");
_amount = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter months:");
_month = Convert.ToInt32(Console.ReadLine());
//Calculting Simple Intrest
_simpleintrest = _amount * _month*_a/ 2 * 12*_b;
_a = _month + 1;
_b = 7.65/100;
//Calculating Maturity Amount
_x = _amount * _month;
_matureAmount = _x + _simpleintrest;
Console.WriteLine("Amount is :{0}",_matureAmount);
}
}
Code link
Output
If you want convert to decimal, you can use the Convert.ToDecimal method.
Console.WriteLine("Amount is :{0}",_matureAmount.ToString("0.00"));
If you want upto 1 decimal place, use .ToString("0.0").
I got the output as expected
New problem how to reduce the place value of final answer
private double p, r = 6.8, i, totalDeposit, maturityAmount;
private int n;
public static void Main(string[] args){
Console.WriteLine("Interest Rate :6.8%");
Console.WriteLine("Please enter per month deposit amount:");
p = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter months:");
n = Convert.ToInt32(Console.ReadLine());
//recurring deposit simple interest formula
//i=p*(n(n+1)/2*12)*r/100
i = p * (n * (n + 1) * r / 2400);
totalDeposit = p * n;
maturityAmount = totalDeposit + i;
Console.WriteLine("Amount of maturity = " +
"Totoal money deposited+Interest:{0}+{1}={2}", totalDeposit, i, maturityAmount);
}
Output
******Recurring Deposit Calculator******
Interest Rate :6.8%
Please enter per month deposit amount:
4567
Enter months:
7
Amount of maturity = Totoal money
deposited+Interest:31969+724.6306666666667=32693.630666666668

C# Compound Interest Calculator (beginner)

C# beginner, trying to create a program where a user enters an amount, years, and rate and then calculates the total amount. The rate will be divided by 100 to get the decimal value and the years will be multiplied by 12 to get the monthly rate.
Here is the code:
class Program
{
static void Main(string[] args)
{
CompoundClass program = new CompoundClass();
Console.Write("Please enter the initial balance for your account: ");
double balance = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the annual interest rate: ");
double interestRate = Convert.ToDouble(Console.ReadLine());
program.Rate(interestRate);
Console.Write("How many years will you acrue interest? ");
double anualAmount = Convert.ToDouble(Console.ReadLine());
program.Years(anualAmount);
Console.WriteLine($"Your balance after {anualAmount} years is {totalAmount:C}\n");
Console.ReadLine();
}
}
class CompoundClass
{
public double rate;
public double yearlyRate;
public double balance;
public void Rate(double interestRate)
{
if (interestRate > 0)
{
rate = interestRate / 100;
}
}
public void Years(double anualAmount)
{
if (anualAmount > 0)
{
yearlyRate = anualAmount * 12;
}
}
public void addMethod(double totalAmount)
{
for (int i = 1; i < yearlyRate + 1; i++)
{
totalAmount = balance * Math.Pow(1 + rate / yearlyRate, yearlyRate * i);
}
}
}
I keep getting the error:
CS0103The name 'totalAmount' does not exist in the current context.
I don't know if any information is being pulled correctly and stored/calculated.
You are having that error because the 'totalAmount' variable can only be accessed inside CompoundClass. This is because it is created with a default access modifier private.
You created an object for CompoundClass
CompoundClass program = new CompoundClass();
You have accessed the methods using the object. Regarding your question for annualAmount or interestRate, you didn't access the variables from CompoundClass, you have just passed them from Program class. However you can still access rate, yearlyRate, and balance through the object like program.rate and so on. This is because you have declared them as public.
public double rate;
public double yearlyRate;
public double balance;
If you want to access totalAmount as well, please declare that as public.
program.addMethod(balance);
Console.WriteLine($"Your balance after {anualAmount} years is {program.totalAmount:C}\n");
You are trying to print out (from program) the value of a variable that you have not declared (totalAmount from within program).
Since it is looking like you want to calculate totalAmount you want to change your addMethod to return the calculated amount instead of accepting totalAmount as a parameter.
For example in program do
double totalAmount = addMethod();
Console.WriteLine($"Your balance after {anualAmount} years is {totalAmount:C}\n");
And implement addMethod to return the value:
public void addMethod()
{
double calculatedTotalAmount = 0;
for (int i = 1; i < yearlyRate + 1; i++)
{
calculatedTotalAmount = balance * Math.Pow(1 + rate / yearlyRate, yearlyRate * i);
}
return calculatedTotalAmount;
}
Effectively, you are assigning the value calculated within the scope of the method to totalAmount, which is declated in the outer scope.

Payroll Array Issues (unsure why calculations do not begin) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
public struct pay
{
public string name;
public int rate;
public int hours;
public int gross;
public int wtd;
public int ssd;
public int md;
public int net;
}
static void Main(string[] args)
{
pay[] myPay = new pay[3];
for (int i = 0; i<= 2; i++)
{
Console.WriteLine("Enter name: ");
myPay[i].name = Console.ReadLine();
Console.WriteLine("Enter pay rate: ");
myPay[i].rate = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter hours worked: ");
myPay[i].hours = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("Name\tRate\tHours\tGross\t W/T\tSS\tMed\tNet");
for (int i = 0; i<=2; i++)
{
int gross = (myPay[i].rate * myPay[i].hours);
int wtd = (myPay[i].gross * (1/20));
int ssd = (myPay[i].gross * (3 / 100));
int md = (myPay[i].gross * (1 / 100));
int net = (myPay[i].gross - (md + ssd + wtd));
Console.WriteLine(myPay[i].name + "\t" + myPay[i].rate + "\t" + myPay[i].hours + "\t" + myPay[i].gross + "\t" + myPay[i].wtd + "\t" + myPay[i].ssd + "\t" + myPay[i].md + "\t" + myPay[i].net);
}
Console.ReadLine();
}
}
The code is intended to take the name, rate, and hours worked of an employee to find gross pay. Then, costs will be taken from gross pay (each indicated with WTD, SD, and MD) to find the net income for the employee.
For whatever reason, the calculations for gross pay never begin, and therefore the following calculations do not register either. Any help would be greatly appreciated!
If you need a decimal value, you cant store it in an int
int (C# Reference)
If you are going to be calculating money you need to use a decimal
decimal (C# Reference)
Struct
public struct pay
{
public string name;
public int rate;
public int hours;
public decimal gross;
public decimal wtd;
public decimal ssd;
public decimal md;
public decimal net;
public void Calculate()
{
gross = (rate * hours);
wtd = (gross * (1 / (decimal)20));
ssd = (gross * (3 / (decimal)100));
md = (gross * (1 / (decimal)100));
net = (gross - (md + ssd + wtd));
}
}
Usage
static void Main(string[] args)
{
pay[] myPay = new pay[3];
for (int i = 0; i <= 2; i++)
{
Console.WriteLine("Enter name: ");
myPay[i].name = Console.ReadLine();
Console.WriteLine("Enter pay rate: ");
myPay[i].rate = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Enter hours worked: ");
myPay[i].hours = Convert.ToInt16(Console.ReadLine());
}
Console.WriteLine("Name\tRate\tHours\tGross\t W/T\tSS\tMed\tNet");
for (int i = 0; i <= 2; i++)
{
myPay[i].Calculate();
Console.WriteLine($"{myPay[i] .name}\t{myPay[i] .rate}\t{myPay[i] .hours}\t{myPay[i] .gross}\t{myPay[i] .wtd}\t{myPay[i] .ssd}\t{myPay[i] .md}\t{myPay[i] .net}");
}
Console.ReadLine();
}
Output
Enter name:
dfg
Enter pay rate:
4
Enter hours worked:
5
Enter name:
dh
Enter pay rate:
56
Enter hours worked:
7
Enter name:
fjh
Enter pay rate:
56
Enter hours worked:
4
Name Rate Hours Gross W/T SS Med Net
dfg 4 5 20 1.00 0.60 0.20 18.20
dh 56 7 392 19.60 11.76 3.92 356.72
fjh 56 4 224 11.20 6.72 2.24 203.84
Disclaimer, i just fixed up the glaring problems, however i am not liable for anyone you maim or otherwise injure with this code
I think your problem is using int as a variable, you should use decimal variable when calculating salaries or anything that involves currency to have exact result.

Calculating percentabe in C# [duplicate]

This question already has answers here:
Division returns zero
(8 answers)
Closed 7 years ago.
I am starting to learn C# and here is a program that calculate percentage
using System;
namespace CheckDegree
{
class Program
{
static void Main(string[] args)
{
int totalmarks=0;
for (int i = 0; i < 5; i++ ) {
Console.WriteLine("Please enter a subject.");
string subject = Console.ReadLine();
Console.WriteLine("Enter the mark for {0}",subject);
int mark = Convert.ToInt32(Console.ReadLine());
totalmarks = totalmarks + mark;
}
double percentage = (totalmarks / 500) * 100;
if (percentage >= 60)
{
Console.WriteLine("You got {0} and has been awarded a first division", percentage );
}
else if (percentage >= 50 && percentage <= 59)
{
Console.WriteLine("You got {0} and has been awarded a second division", percentage);
}
else if (percentage < 40 )
{
Console.WriteLine("You got {0} and thus have failed!!!", percentage);
}
Console.ReadKey();
}
}
}
However percentage always output 0
double percentage = (totalmarks / 500) * 100;
Instead of dividing by 500, divide by 500.0. It's treating it as an integer divided by an integer, which will be 0.#####. Since it's an integer, the decimal gets dropped. Then, 0 times 100 is still 0.
Changing 500 to 500.0 will force the division to be a double, which will preserve your decimal value.

C# value is always 0 console application

I have no idea why my BMI value is always = to 0. I am programming noob what am i missing? other than that is my if statement alright? what am i missing?
static void Main(string[] args) {
double WeightKg = 0.0, HeightCm = 0.0, Weightlbs = 0.0, WeightOz = 0.0, BMI = 0.0, Feet = 0.0, Inches = 0.0;
int BMIOption;
string AnotherConversion;
string BMIMenu = ("Which Measurement You Want to use to enter the weight and height?"
+ "\n1)Enter 1 for Metric"
+ "\n2)Enter 2 for British Imperial:");
Console.Write(BMIMenu);
BMIOption = int.Parse(Console.ReadLine());
if (BMIOption == 1) {
Console.Write("\nPlease Enter your Weight in Kilogram (kg):");
WeightKg = int.Parse(Console.ReadLine());
Console.Write("\nPlease Enter your Height in in centimetres (cm):");
HeightCm = int.Parse(Console.ReadLine());
BMI = WeightKg / (HeightCm * HeightCm);
if (BMI >= 35) {
Console.WriteLine("\nYour BMI is {0:C},Severe Obesity", BMI);
} else if (BMI >= 30) {
Console.WriteLine("\nYour BMI is {0:C},Obese", BMI);
} else if (BMI >= 25) {
Console.WriteLine("\nYour BMI is {0:C},OverWeight", BMI);
} else if (BMI >= 18.5) {
Console.WriteLine("\nYour BMI is {0:C},Healthy BodyWeight", BMI);
} else if (BMI <= 18.5) {
Console.WriteLine("\nYour BMI is {0:C},UnderWeight", BMI);
}//End if
Console.Write("\nWould you like to make an another conversion? \n\n(Enter Y to make an another conversion/Enter any other key to exit):");
Console.ReadKey();
BMI is calculated with meters, not centimeters. So you need to convert the HeightCm to HeightM. If you don't do this, you get really small number, that is then printed as 0.
double HeightM = HeightCm / 100.0;
BMI = WeightKg / (HeightM * HeightM);
Also, when parsing, use double.Parse instead of int.Parse. The way it is right now, you will only parse the number without the decimal part.
In this line:
BMI = WeightKg / (HeightCm * HeightCm);
The result ends up being very small (less than 1). Take an example where WeightKg is 55 and HeightCm is 165. The result is around 0.002.
When you display it as {0:C}, it's being displayed as zero. Use {0:G} to see the actual value.
even so your formula is wrong, as Martin says u must replace the int.Parse with double AND
BMI = WeightKg / ((HeightCm/100) * (HeightCm/100));
use this for calculation it is HEIGHT IN METERS :)

Categories