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.
Related
so I am trying to create a C# program that asks for a value between 1 and 100 that uses a loop to determine the sum of all values between 1 and the entered value and if the number entered in is less than one or more than 100 it prints out "Sorry. Try again." I've been working on this for days but I can't get it to print the sum, I keep getting 0 and whenever I test it and enter a number under one or over 100, it won't print the error message I want. Here is the code:
using System;
namespace PrintSumL
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a beginning value between 1 and 100");
int s = Convert.ToInt32(Console.ReadLine());
int sum = 0;
Console.WriteLine("Sum of values: " + sum);
Console.ReadKey();
Random rand = new Random();
rand.Next(1, 51);
while (0 < s && s < 101)
{
sum += s;
s++;
if (s < 0 && 101 < s)
{
Console.WriteLine("Invalid input. Try again.");
}
{
}
{
}
}
}
}
}
You can think of the program as executing line by line from top to bottom, and only moving back up when it reaches the end of the while loop. The end of the while loop is the } that matches the { at the start of the loop.
Knowing that, you can see why it always says sum is zero. From your code:
int sum = 0;
Console.WriteLine("Sum of values: " + sum);
Since the program executes "line by line from top to bottom", it will first set sum to 0, and then print sum out. So it will always print "Sum of values: 0". If you want it to print out the sum after it has calculated it, then you need to move the WriteLine down below where the sum is calculated.
The same issue applies to the "Invalid input. Try again.": the line that prints this statement appears after while (0 < s && s < 101), so will only execute if s is between 0 and 101. Since you're trying to catch the scenario where s is not between 0 and 101, you'll need to move the statement to above the while loop.
So, to fix your immediate problems, just do two things:
1) move the two lines
Console.WriteLine("Sum of values: " + sum);
Console.ReadKey();
to after the while loop (just after the } which is at the same level of indentation as while).
2) move the three lines
if (s < 0 && 101 < s)
{
Console.WriteLine("Invalid input. Try again.");
}
up to just below int s = Convert.ToInt32(Console.ReadLine());, and then double check the logic. It sounds like you want to print the statement if s is less than zero or s is greater than 101.
if loops are a requirement you should follow Heath Raftery instruction
else you could write something like:
static void Main(string[] args)
{
Console.WriteLine("Enter a beginning value between 1 and 100");
int s = Convert.ToInt32(Console.ReadLine());
if (s < 0 || s > 100)
Console.WriteLine("Invalid input. Try again.");
else
Console.WriteLine($"Sum of values: {Enumerable.Range(1,s).Sum()}");
}
or as haldo commented you could just use the formula of N * (N+1) / 2 and replace the last WriteLine with:
Console.WriteLine($"Sum of values: {s * (s+1) / 2}")
Try this:
static void Main(string[] args)
{
while (true)
{
Console.Write("Enter a number between 1 and 100: ");
int Number = Convert.ToInt32(Console.ReadLine());
if (Number < 0 || Number > 100)
Console.WriteLine("Sorry. Try again.");
else
{
int sum = 0;
for (int i = 1; i <= Number; i++)
{
sum = sum + i;
}
Console.WriteLine("Sum of values: " + sum);
}
}
}
Here is an algorithm that works...
Console.WriteLine("Enter a value between 1 and 100");
var input = int.Parse(Console.ReadLine());
int sum = 0;
if (input<1 || input>100) {
Console.WriteLine("Sorry, Try again");
}
else{
while(input > 2){
input-=1;
sum+=input;
}
}
Console.WriteLine("Sum of values: " + sum);
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 5 years ago.
I'm working on a program for my C# class that is supposed to take an entered amount, as a double or not, and to find change in dollars, quarters, etc.,
I'm using the Greedy Algorithm, and I keep getting some sort of error that reads, "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in 2D.exe".
I'm still relatively new to C#, and come from a Java and C++ Background.
So far I have my Money class:
using System;
using static System.Console;
namespace _2D
{
class Money
{
private double dollars, cents;
public void IncrementMoney() { }
public void DecrementMoney() { }
public Money(double dollarsncents)
{
double amountLeftOfDecimal = Math.Truncate(dollarsncents);
double amountRightOfDecimal = Math.Floor(dollarsncents);
this.dollars = Math.Round(amountLeftOfDecimal);
//the following LOGIC needs to be wokred out:
this.cents = Math.Round((amountRightOfDecimal * 100) / 100, 2);
}
public Money(int ddollars, int ccents)
{
this.dollars = ddollars;
this.cents = ccents;
}
public override string ToString()
{
return String.Format(dollars + " dollars and " + cents + " cents.");
}
public void CoinAmounts(int inAmount, int remainder, int[] coins)
{
if((inAmount % 0.25) < inAmount)
{
coins[3] = (int)(inAmount / 0.25);
remainder = inAmount % (1/4);
inAmount = remainder;
}
if ((inAmount % 0.1) < inAmount)
{
coins[2] = (int)(inAmount / 0.1);
remainder = inAmount % (1/10);
inAmount = remainder;
}
if ((inAmount % 0.05) < inAmount)
{
coins[1] = (int)(inAmount / 0.05);
remainder = inAmount % (1/20);
inAmount = remainder;
}
if ((inAmount % 0.01) < inAmount)
{
coins[0] = (int)(inAmount / 0.01);
remainder = inAmount % (1/100);
}
}
public void PrintChange(int[] arr)
{
if (arr[3] > 0)
Console.WriteLine("Number of quarters: " + arr[3]);
if (arr[2] > 0)
Console.WriteLine("Number of dimes: " + arr[2]);
if (arr[1] > 0)
Console.WriteLine("Number of nickels: " + arr[1]);
if (arr[0] > 0)
Console.WriteLine("Number of pennies: " + arr[0]);
}
}
And my Main :
using System;
namespace _2D
{
class Program
{
static void Main(string[] args)
{
Money MyMoney = new Money(23, 24);
Console.WriteLine(MyMoney.ToString());
Money dollarCentAmount = new Money(12.45);
Console.WriteLine(dollarCentAmount.ToString());
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
Console.Clear();
Console.WriteLine("Enter an amount you'd like change for: ");
double inAmountDouble = Convert.ToDouble(Console.ReadLine());
int inAmount = Convert.ToInt32(inAmountDouble);
int tochange = inAmount;
int remainder = 0;
int[] coins = new int[3];
MyMoney.CoinAmounts(inAmount, remainder, coins);
Console.WriteLine(" Change for " + inAmount + " is: ");
if (inAmount > 1.0)
{
Console.WriteLine("Number of dollars: " + Convert.ToInt32(inAmount));
}
MyMoney.PrintChange(coins);
Console.ReadKey();
}
}
}
You declared coins to be an array going from 0 to 2
array[size] //size is how many elements are in the array, not the upper bound of the array
coins[3] //means the array contains three elements, elements: 0, 1, 2
//so you want:
int[] coins = new int[4]; //Goes from 0 to 3, elements: 0, 1, 2, 3
//This will allow you to later access:
//since coins[3] is the 4th element, this is as high as the array can go now
coins[3] = (int)(inAmount / 0.25);
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.
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.
I am revisiting one of my old exercises and I seem to be having problems with my logic. It is a simple console application that is supposed to calculate and display change for a given total and cash tendered. For some reason, I get an infinite loop when I input values which decimal part other than 25.
Here is a screenshot of my console application
Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace James_Archbold_A2
{
class Program
{
static void Main(string[] args)
{
double change,total,cash;
int fifties = 0, twenties = 0, tens = 0, fives = 0, ones = 0,
quarters = 0, dimes = 0, nickels = 0, pennies = 0;
Console.Write("Please enter the total: ");
total = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the cash tendered: ");
cash = Convert.ToDouble((Console.ReadLine()));
change = CalculateChange(total, cash);
Console.WriteLine(change);
change *= 100;
while (change > 0)
{
if (change >= 5000)
{
change -= 5000;
fifties++;
Console.WriteLine(change);
}
else if (change >= 2000)
{
change -=2000;
twenties++;
Console.WriteLine(change);
}
else if (change >= 1000)
{
change -=1000;
tens++;
Console.WriteLine(change);
}
else if (change >= 500)
{
change -= 500;
fives++;
Console.WriteLine(change);
}
else if (change >= 100)
{
change -=100;
ones++;
Console.WriteLine(change);
}
else if (change >= 25)
{
change -=25;
quarters++;
Console.WriteLine(change);
}
else if (change >= 10)
{
change -=10;
dimes++;
Console.WriteLine(change);
}
else if (change >= 5)
{
change -=5;
nickels++;
Console.WriteLine(change);
}
else if (change >= 1)
{
change -=1;
pennies++;
Console.WriteLine(change);
}
}
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Total: {0:c}\nCash Tendered: {1:c}" +
"\nChange Due: \nFifties: {2}\nTwenties: {3}\nTens: {4}" +
"\nFives: {5}\nOnes: {6}\nQuarters: {7}\nDimes: {8}" +
"\nNickels: {9}\nPennies: {10}",
total, cash, fifties, twenties, tens, fives, ones, quarters, dimes,nickels, pennies);
Console.WriteLine(sb);
Console.ReadLine();
}
static double CalculateChange(double total, double cash)
{
return cash - total;
}
}
}
If you're writing anything to do with financial calculation, use the decimal data-type. Not double.
I think Jon Skeet's article "Binary floating point and .NET" will give you the greatest insight.
A few other pointers:
Is a double really unsuitable for money?
What Every Computer Scientist Should Know About Floating Point
Make change an int to truncate the .0000000000001 that prevents change from ever falling below 0 with your current algorithm:
int change = CalculateChange(total, cash) * 100;
Use change>=0 in while condition
You're using doubles for your arithmetic, you can't rely on exact precision for decimal input using doubles.
If you want to use floating points with decimal, you should use C# decimal type.
In the code snippet provided just round the value of the variable change to its nearest integer and you would get the required output.
From
`while (change > 0)`
to
`while(Math.Round(change)>0)`
Hope this helps