Body Mass Index program console window version since im learning with Programming 1 course its essentially before object oriented stuff.
i cant seem to understand what im doing wrong as it says
Error CS0019 Operator '^' cannot be applied to operands of type 'double' and 'double
and i have no clue what im doing wrong and are completely lost! :(
namespace BMI_o_BMR
{
internal class Program
{
static void Main(string[] args)
{
double weight, height, bmi, bmr;
string gender; // Female f = kvinna, male m = man
Console.WriteLine("Vi ska räkna ut ditt BMI och BMR");
Console.WriteLine("Write your height");
weight = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Write Your weight");
height = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Write your age");
int age = Convert.ToInt32(Console.ReadLine());
if (height >= 0.50 && height <= 2.20 && weight >= 10 && weight <= 250 && age >= 18 && age <= 70)
{
bmi = (weight * 1.3) / height ^ 2.5;
Console.WriteLine(bmi);
}
Console.WriteLine("choose your Gender M for Male or F for Female");
}
}
}
In C# ^ is either a boolean logical XOR or bitwise logical XOR (C# operators and expressions).
Use Math.Pow:
Returns a specified number raised to the specified power.
bmi = (weight * 1.3) / Math.Pow(height, 2.5);
Related
I am trying to create a code that allows me to calculate the price of two products however there are some changes throughout the code, (I want to aplly discounts according to the volume that will be bought. However when I make counts with three variables it show use of unassigned local variable...
static void Main(string[] args)
{
double peso_morango, peso_maca, total;
double totalmorango, totalmaca, final_real;
const double percentual = 0.1;
Console.WriteLine("Insira a quantidade de morangos, em kg: ");
peso_morango = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insira a quantidade de maça, em kg:");
peso_maca = Convert.ToInt32(Console.ReadLine());
if (peso_morango <= 5)
{
totalmorango = 2.50 * peso_morango;
}
else if (peso_morango > 5)
{
totalmorango = 2.20 * peso_morango;
}
else if (peso_morango > 8)
{
totalmorango = 1.62 * peso_morango;
}
else if (peso_maca <= 5)
{
totalmaca = 1.62 * peso_maca;
}
else if (peso_maca > 5)
{
totalmaca = 2.20 * peso_maca;
}
else if (peso_maca > 8)
{
totalmaca = 1.35 * peso_maca;
}
else if (peso_maca + peso_morango > 8)
{
total = totalmorango + totalmaca;
final_real = (total) - (percentual * total);
Console.WriteLine(" O valor final é de {0} euros", final_real);
}
else if (totalmaca + totalmorango > 25)
{
total = totalmorango + totalmaca;
final_real = (total) - (percentual * total);
Console.WriteLine(" O valor final é de {0} euros", final_real);
}
else if (peso_maca + peso_morango < 8)
{
Console.WriteLine(" O valor final é de {0} euros", final_real);
}
else if (totalmorango + totalmaca < 25)
{
Console.WriteLine(" O valor final é de {0} euros", final_real);
}
Console.ReadKey();
}
I understand this is not a solution to your problem, but the only part of the code which will run is:
static void Main(string[] args)
{
double peso_morango, peso_maca, total;
double totalmorango, totalmaca, final_real;
const double percentual = 0.1;
Console.WriteLine("Insira a quantidade de morangos, em kg: ");
peso_morango = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insira a quantidade de maça, em kg:");
peso_maca = Convert.ToInt32(Console.ReadLine());
if (peso_morango <= 5)
{
totalmorango = 2.50 * peso_morango;
}
else if (peso_morango > 5)
{
totalmorango = 2.20 * peso_morango;
}
Console.ReadKey();
}
This is because EITHER peso_morango <= 5 OR peso_morango > 5 will be true.
I don't think "else if" does what you expect it to do.
To make such mistake means that you're a beginner in programming and you'll probably do with some explanation to what is happening.
We gonna use int for this example.
When you declare variable like this int x; that is basically say hey i need some memory allocate some for me, How much of memory depend on the int
Now if you ever done some C++ or any unmanaged programming languages (Means the compiler doesn't do half of the work for you), you would understand that
int x; in memory will actually be holding some values from previous operations we don't know about, So you'll have to explicitly clean it from that garbage.
In C# that is basically the same, however here we have the compiler complaining to help you out, since you want some memory it needs to be fresh so you'll have to zero it out int x = 0;
So you'll have to zero it out or assign it a value you want to start with, you can use negative values too if you want to keep the zero, depending on the Valuetype int or uint etc....
totalmorango and totalmaca are not initialized, they are just declared. You need to initialize your variables with proper Initial values first before you use it.
By looking into your code, you are using them in addition operation.
assuming if any if elseif are not satisfy (where you assign value to them), you need them to be 0. (also it is unit value for addition operation)
replace your line
double totalmorango, totalmaca, final_real;
with
double totalmorango = 0, totalmaca = 0, final_real = 0;
Update
however whatever error you are facing will be solved by above steps, but as mentioned by others too. your checking ,
else if (peso_morango > 5)
is not appropriate if you want to check if value of peso_morango is greater than 5 but also if you want that to be less or equal to 8.
you should be checking else if (peso_morango > 5 && peso_morango <= 8)
And also you should be having separate condition checking for peso_maca . like,
if (peso_maca <= 5)
{
totalmaca = 1.62 * peso_maca;
}
else if (peso_maca > 5 && peso_maca <= 8)
{
totalmaca = 2.20 * peso_maca;
}
else// no need to check else part "peso_maca > 8" as it always be true
{
totalmaca = 1.35 * peso_maca;
}
and same way, separate condition checking for later part too.
By doing this, you will not even need to do,
double totalmorango = 0, totalmaca = 0, final_real = 0;
as suggested in first part of answer.
Noob here. I have written a program that allows a user to enter how many grades they would like to input into an array, and then lets them enter the grades for the number of indexes they chose. I am trying to output the total percentage grade based on the inputted grades, and also output the actual letter grade, but I am having trouble figuring out what I would code to convert to letter grades. Any help is appreciated.
Code:
public static void Main(string[] args)
{
int ARRAYLENGTH = 0;
int i = 0;
double sum = 0;
Console.WriteLine("How many scores would you like to enter? ");
ARRAYLENGTH = Convert.ToInt32(Console.ReadLine());
string[] test = new string[ARRAYLENGTH];
for (i = 0; i < test.Length; i++)
{
Console.Write("Enter your test score " + (i + 1) + ": ");
test[i] =
Console.ReadLine();
}
for (i = 0; i < test.Length; i++)
{
sum = sum +
Convert.ToDouble(test[i].Trim());
}
Console.WriteLine("\nThis is your average = " + (sum / test.Length));
Console.WriteLine("\nYour grade is: ");//Not sure how this would work
Console.Write("\nPress the [Enter] key to exit.");
Console.ReadLine();
}
For one, you're better of doing some more assignment (rather than calculating the grade in the print statement) so I've included that below. Once you have the percentage in a var you just use an if/else or a switch to derive the letter grade.
double gradePer = sum / test.Length
string gradeLetter = "F";
if (gradePer >= 60 && gradePer < 70) {
gradeLetter = "D";
} else if (gradePer >= 70 && gradePer < 80) {
gradeLetter = "C";
} // you fill in the rest
Console.WriteLine("\nThis is your average = " + gradePer);
Console.WriteLine("\nYour grade is: " + gradeLetter);
I would use a switch, specificing a range of values for each letter
You can make a function to get your letter grade from the average you computed:
static char GetLetterGrade(double score)
{
if (score >= 90.0)
{
return 'A';
}
if (score >= 80.0)
{
return 'B';
}
if (score >= 70.0)
{
return 'C';
}
if (score >= 60.0)
{
return 'D';
}
return 'F';
}
In the simplest possible way... I would create a dictionary:
Key - Value
10 - A
9 - A
8 - B
7 - C
6 - D
5 - F
4 - F
3 - F
2 - F
1 - F
0 - F
Now that you have this dictionary set up, you can take the grade into your method, divide by 10, take the floor and find the entry associated with that value.
public class Grades
{
Dictionary<int, char> GradeValues { get; set; }
public Grades()
{
GradeValues.Add(10, 'A');
GradeValues.Add(9, 'A');
GradeValues.Add(8, 'B');
...
GradeValues.Add(0, 'F');
}
public char GetGrade(int grade)
{
char value = GradeValues[int.Floor(grade/10)];
if (value == null)
return 'F';
return value;
}
}
That being said, there are probably better ways to handle this.
Edit: This assumes that you don't have B- or other grades that happen when a grade of 88 is passed into the method.
If statements or cases would work great too, but I prefer this method of development. It is easier to extend when you want to change a grade. You don't have to update the method. You only need to update the dictionary in the constructor.
Edit 2: I have seen that someone downvoted every answer. I upvoted the other answers as they are all valid...
You could just fill out the entire dictionary from 0 to 100 with the grade for that score.
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.
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 :)
I just started programming a week ago and my first assignment was to code a BMI calculator.
It is supposed to look like this when launched:
BMI Calculator
Your weight in kg: x
Your height in cm: x
Gender (m/f): x
-> You are underweight/normal/overweight
Here is my code so far:
Console.WriteLine("BMI Calculator");
Console.WriteLine("===========");
Console.WriteLine();
Console.Write("Weight in kg: ");
int kg;
kg = Convert.ToInt32(Console.ReadLine());
Console.Write("Height in cm: ");
int m;
m = Convert.ToInt32(Console.ReadLine());
Console.Write("Gender (m/f):");
string Geschlecht = Console.ReadLine();
int BMI;
BMI = kg / (m / 100) * (m / 100);
if (BMI < 19 & Gender == "f")
{ Console.WriteLine("-> Underweight"); }
if (BMI >= 19 & BMI <= 24 & Gender == "f")
{ Console.WriteLine("-> Normal"); }
if (BMI > 24 & Geschlecht == "f")
{ Console.WriteLine("-> Overweight"); }
if (BMI < 20 & Gender == "m")
{ Console.WriteLine("-> Underweight"); }
if (BMI >= 20 & BMI <= 25 & Gender == "m")
{ Console.WriteLine("-> Normal"); }
if (BMI > 25 & Gendert == "m")
{ Console.WriteLine("-> Overweight"); }
Console.ReadLine();
I'm not sure what's wrong with my code but whenever I enter 60kgs, 170cm and male, I get overweight, even though I should get normal. Same thing with anything above 10kgs actually.
PS: I'm really a beginner at programming so I apologize for my command of the programming lingo.
And for your convenience:
http://i.stack.imgur.com/admqr.png
Thanks in advance!
When you do:
BMI = kg / (m / 100) * (m / 100);
And m is an int, you'd be doing integer division, in which case 170 / 100 = 1. And as User1551892 pointed out, you'll need to be a bit more specific about the order of calculations.
Try:
double BMI = kg / ( ( m / 100.0 ) * ( m / 100.0 ) );
That will force it to do floating point division and should get you better results.
Also, you could use Math.Pow to avoid having m / 100.0 twice:
double BMI = kg / Math.Pow( m / 100.0, 2 );
Please check this line:
BMI = kg / (m / 100) * (m / 100);
it should be like this:
BMI = kg / ((m / 100) * (m / 100)) ;
FYI new stack's exchange portal has opened : codereview.stackexchange.com
It should be better place to ask for review
the calculation is off though for BMI. it is (weight/height)/height
so
int bmi = (kg/(m/100))/(m/100)
Check Your gender's variable in each IF statement...