How to round to the nearest thousandth using C# - c#

I am an extreme beginner when it comes to coding, and I am building a batting average calculator as one of my first programs.
Console.WriteLine("Your batting average is: " + (hits / atBats) );
The input for hits is 165 and 419 for atBats, and it calculates to .3937947494. Though this is correct, I would like the number to read as .394. How would I do that?

A sample example that demonstrates usage of Math.Round() function:
using System;
class MainClass {
public static void Main (string[] args) {
double result = 0.3937947494;
Console.WriteLine(Math.Round(result,3));
}
}
// here result is = 0.3937947494, but you will get output as 0.394 in the console.
VERSION 2:
using System;
public class Program
{
public static void Main()
{
int hits = 165;
int atBats = 419;
double result = (double)hits / (double)atBats;
Console.WriteLine("Your batting average is: " +Math.Round(result,3));
}
}
// this produces the same result
// Your batting average is: 0.394
Screenshot for second alternative:
VERSION 3: Serves better readability (as suggested correctly by #Manti_Core
using System;
public class Program
{
public static void Main()
{
double hits = 165;
double atBats = 419;
double result = hits/atBats;
Console.WriteLine("Your batting average is: " + (hits / atBats).ToString("0.000"));
}
}
Hope this helps.

You can use string.Format:
var number = 0.3937947494;
Console.WriteLine(string.Format("{0:0.000}", number));

You can do simple like below :
double hits = 165;
double atBats = 419;
Console.WriteLine("Your batting average is: " + (hits / atBats).ToString("#.000"));
Console.Read();
here your are simply formatting the value that you want to display.
Performance of string format vs boxing values :
String format
Boxing values

Related

How Can I sum all digits in a number using loop?

when I enter 1 for n
and 1111 for lines
the sum must be 1+1+1+1=4 but the output is 1.
THIS IS THE QUESTION...
you will get a (n) then (n) lines as an input, In each line there are some numbers (we don’t know how many they are) and you must print (n) lines, In the i-th line print the sum of numbers in the i-th line.
using System;
namespace prom2
{
class Program
{
static void Main(string[] args)
{
int lines=0, sum = 0;
Console.Write("Enter a number of lines ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n&n>0&1000>n; i++)
{
Console.WriteLine("Enter line " + i + " numbers");
lines = int.Parse(Console.ReadLine());
lines = lines / 10;
sum += lines % 10;
Console.WriteLine("sum is " + sum);
}
}
}
}
Try this:
static void Main(string[] args)
{
int input;
bool times = true;
List<int> numbers = new List<int>();
while (times)
{
Console.Clear();
Console.WriteLine("Enter number: ");
var num = int.TryParse(Console.ReadLine(), out input);//tryparse will output a bool into num and set input to a int
if (num)
{
numbers.Add(input);//only integers will be added to list
}
Console.Clear();
Console.WriteLine("Another? Y or N");//ask if they want to sum more numbers
var yesno = Console.ReadLine();//get answer from user
if (yesno.ToUpper().Trim() != "Y")//if N or anything else
{
//assume no
times = false;
}
Console.Clear();
}
var sum = numbers.Sum();
Console.WriteLine("Sum : " + sum.ToString());
Console.ReadLine();//just to pause screen
}
Because Console.ReadLine returns a string, and it's possible to treat a string as if it's an array of chars (where char represents a single character), you can have a method like this to calculate the sum of all the digits in a single line:
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
Please note this method contains no validation - ideally you should validate that line is purely numeric, otherwise int.Parse will throw an exception, although the same is true of the code you provided too.
If you want to work with multiple lines of console input, just call this method from within another loop which solicits / works through those lines of console input.
Edit
My answer doesn't answer all of your question, it only answers the part which asks how to calculate the sum of the digits in a numeric string, and it does work, to the extent that it correctly does what it says on the tin.
Here's all the code I wrote to validate the answer before posting the original answer (I wrote it as a xUnit unit test rather than a console application, but that doesn't change the fact that the code I shared works):
using System;
using Xunit;
namespace StackOverflow71442136SumDigits
{
public class UnitTest1
{
[Theory]
[InlineData("1", 1)]
[InlineData("12", 3)]
[InlineData("23", 5)]
[InlineData("1234", 10)]
[InlineData("123456789", 45)]
public void Test1(string line, int expectedSum)
{
var actualSum = this.SumTheDigits(line);
Assert.Equal(expectedSum, actualSum);
}
private int SumTheDigits(string line)
{
var sum = 0;
foreach (var character in line)
{
sum += int.Parse(character.ToString());
}
return sum;
}
}
}
You might want to read How do I ask and answer homework questions?

after do... while loop Unhandled Exception: System.FormatException: Input string was not in a correct format

So my lab is supposed to ask you how many questions you want and then give you that many randomly generated math problems. At the end it should ask you if you want to have another set of questions or just end and you have the option to answer y or n. when i stop the code there everything works fine but I also need to get the total amount correct printed and when I add that code I get the Unhandled Exception. My problems come from the last three lines before the brackets:
using System;
class MainClass {
public static void Main (string[] args) {
var rnd = new Random();
string exit = "";
double score = 0;
double total = 0;
double percent = 0;
Console.WriteLine("How many problems do you want in a set?");
double problem = Convert.ToDouble(Console.ReadLine());
do{
for(double i = 1; i<=problem; i++){
double num1 = rnd.Next(1,9);
double num2 = rnd.Next(1,9);
Console.Write("Problem {0} : {1}*{2}=? ", i, num1, num2);
double answer = Convert.ToDouble(Console.ReadLine());
if(num1*num2 == answer){
score++;
}//end if
total++;
}
Console.Write("Another set? <y/n>");
exit = Console.ReadLine();
Console.ReadLine();
}while(exit!="n");
percent = score/total;
Console.WriteLine(" {} correct out of {} is a {}%",score,total,percent);
Console.WriteLine("done");
}//end main
}//end class
Either number the parameters {0}, {1}, {2}, or you can now use string interpolation as follows:
Console.WriteLine($"{score} correct out of {total} is a {percent}%");
Console.WriteLine(" {} correct out of {} is a {}%",score,total,percent);
needed 0, 1, and 2

How do i invoke a method in c#?

I need to invoke a method to then print it, right now i get .NaN as the output when you enter the right temperature.
using System;
using System.Security.Cryptography.X509Certificates;
namespace Bastun2
{
class Pogram
{
public static void Main(string[] args)
{
double temperatureF = double.NaN;
double temperatureC = double.NaN;
string input = string.Empty;
bool inputIsOkay = false;
while (!inputIsOkay) //Tells you to repeat until input is true
{
Console.WriteLine("Enter temperature in numbers."); //Asks for temperature
input = Console.ReadLine(); //Input temperature
if (!double.TryParse(input, out temperatureF)) //Prevents you for using letters
{
Console.WriteLine($"'{input}' is not a valid input. Use numbers and , not ."); //Tells you not to use letter or "."
}
else if (temperatureF < 163.4)//Repeat if temperature is under 163.4
{
//temperatureC = (temperatureF - 32) * 5 / 9; //Converts Farneheight to Celcius
Console.WriteLine($"Temperature is to low, enter a higher temperature."); //Tells you that temperature is to low and asks you to input a higher temperature
}
else if (temperatureF > 170.6)//Repeat if temperature is to high
{
//temperatureC = (temperatureF - 32) * 5 / 9; //Converts Farneheight to Celcius
Console.WriteLine($"Temperature is to high, enter a lower temperature.");//Tells you that temperature is to high and asks you to input a lower temperature
}
else
{
inputIsOkay = true; //kick you out of the loop if input is true
}
}
//temperatureC = (temperatureF - 32) * 5 / 9; //Converts Farneheight to Celcius
//Console.ReadLine(calculateC);
Console.WriteLine($"{temperatureC}°C, temperature is within acceptable parameters");//prints C and tell you that temperature is acceptable
}
public static double CToF(double temperatureF, double temperatureC)
{
temperatureC = (temperatureF - 32) * 5 / 9;
return temperatureC;
}
}
}
Based on your replies to the original, I can see an obvious problem from the get go. You're never setting the value for the temperatureC variable which is why you're always getting NaN as you're output when you're trying to print it.
You're already invoking a lot of methods by calling them such as Console.WriteLine(...), etc.
All you need to do is this at the bottom of the Main method under the while loop:
temperatureC = CToF(temperatureF, temperatureC);
And then output the value of temperatureC like you are doing with:
Console.WriteLine($"{temperatureC}°C, temperature is within acceptable parameters");
Another small suggestion to make your code a little more efficient as well as readable is to change your CToF method and just do this:
public static double CToF(double temperatureF)
{
return (temperatureF - 32) * 5 / 9;
}
If you decide to accept that idea of improvement, you can then just invoke the method like so:
temperatureC = CToF(temperatureF);

C# Pass an integer variable with an optional default value

class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
WriteLine("The area of your circle is: " +
circleArea(Double.Parse(ReadLine())).ToString());
ReadKey();
}
static double circleArea(double radius = 5.00)
{
return Math.PI * (radius * radius);
}
}
I thought I had it set up correctly; however, I receive an error of System.FormatException: 'Input string was not in a correct format. on the line WriteLine("The area of your circle is: " + circleArea(Double.Parse(ReadLine())).ToString()); when no value is entered. I would like it to have a default value of 2. Thanks.
Your problem is that you need to split out the conversion to be able to test for a bad input condition. Take a look at this code.
Console.WriteLine("What is the radius of your circle: ");
var isNumber = Double.TryParse(Console.ReadLine(), out double number);
if (!isNumber)
number = 0;
Console.WriteLine("The area of your circle is: " + circleArea(number).ToString());
Console.ReadKey();
This will test for a legitimate number and if it's not, it just passes zero as the number.
Double.Parse() will always throw a FormatException if the input is not in the form of a valid double.
The behavior of default parameter values is that omitting the parameter when calling the method will cause it to instead use the default value (this is done by inserting the default value into the method call at compile-time). There is no language behavior which would enable an invalid value to be automatically replaced by some default.
In your case, you need to preempt the empty value which is going to Double.Parse(). Something like this:
class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
var input = ReadLine();
if (!double.TryParse(input, out var value))
WriteLine($"Invalid input received: {value}");
else
WriteLine("The area of your circle is: " + circleArea(value).ToString());
ReadKey();
}
static double circleArea(double radius = 5.00)
{
return Math.PI * (radius * radius);
}
}
Here's a concise way of testing the input and selecting a default if whatever was input is in an incorrect format.
Console.Write("What is the radius of your circle: ");
var value = double.TryParse(Console.ReadLine(), out var input) ? input : 2d;
Console.WriteLine($"The area of your circle is {circleArea(value)}");
I'd highly advice to do the reading and calculation in two steps
class Program
{
static void Main(string[] args)
{
WriteLine("What is the radius of your circle: ");
var input = ReadLine();
double d = 0.0;
if(!Double.TryParse(input,out d)) {
d = //default value here
}
WriteLine("The area of your circle is: " + circleArea(d).ToString());
ReadKey();
}
}

Is there a way to call a variable from a different method?

I am trying to build a BMI calculator and I the only thing that can be in the main function is method calls. Whenever i run the following code, the calculation answer does not print. How can i fix that?
public static Double EnterWeight(object sender, EventArgs e)
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight(object sender, EventArgs e)
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight(object sender, EventArgs e);
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
Console.WriteLine("Your BMI is: ", BMI);
}
There are some extra lines in the mine that I used for testing.
The result is just a blank
It looks like there are several problems with the code, though they are small. First, you define methods that take in parameters that are not used, like object sender and EventArgs e. You should only define arguments to a method if they are used inside the method, so you can remove those in your case.
Secondly, when you call EnterWeight, you're defining the variables inside the method call, rather than defining them before-hand and then passing them in using the variable names (which would be the way to solve this issue). But since the method doesn't actually require them, they can be removed from the method and therefore removed from the call.
Finally, when writing methods to get strongly-typed input from the user, it is sometimes nice to create a more flexible method that takes in a string used for the "prompt" for the input, and then use the TryParse methods in a loop, which continually loops until they enter valid input. This way you can re-use the same method to get a double from the user and just pass in different prompts.
For example:
private static string GetStringFromUser(string prompt)
{
Console.Write(prompt);
return Console.ReadLine();
}
private static double GetDoubleFromUser(string prompt)
{
double input;
// double.TryParse attempts to convert a string into a double, and
// it returns a bool that indicates success. If it's successful,
// then the out parameter will contain the converted value. Here
// we loop until we get a successful result, then we return the value.
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out input));
return input;
}
public static double GetBMI(double height, double weight)
{
return weight / Math.Pow(height, 2) * 703;
}
private static ConsoleKeyInfo GetKeyFromUser(string prompt)
{
Console.Write(prompt);
var key = Console.ReadKey();
Console.WriteLine();
return key;
}
private static void Main()
{
string name = GetStringFromUser("Enter your name: ");
double weight = GetDoubleFromUser("Enter your weight in pounds: ");
double height = GetDoubleFromUser("Enter your height in inches: ");
double bmi = GetBMI(height, weight);
Console.WriteLine($"Thank you, {name}. Your BMI is: {bmi}");
GetKeyFromUser("\n\nDone! Press any key to exit...");
}
You are using the Console.WriteLine incorrectly. You need to use {argumentNumber} to indicate what argument to print and where in the string. Considering the following (I had to make some additional adjustments to get your code to compile. However, to answer your direct question, your BMI is not printing out because you are using Console.WriteLine slightly wrong.
public static Double EnterWeight()
{
Console.Write("Enter Your Wieght In Pounds: ");
double Rweight = Convert.ToDouble(Console.ReadLine());
return Rweight;
}
public static double EnterHeight()
{
Console.Write("Enter Your Height in Inches: ");
double Rheight = Convert.ToDouble(Console.ReadLine());
return Rheight;
}
public static double Calculation(double height, double weight)
{
double BMI = (weight / Math.Pow(height, 2) * 703);
return BMI;
}
static void Main(string[] args)
{
//string name = EnterName();
//Console.WriteLine(name);
double weight = EnterWeight();
//Console.WriteLine(weight);
double height = EnterHeight();
//Console.WriteLine(height);
double BMI = Calculation(height, weight);
// Notice the {0}. I tell it where in the string to print the
// argument I passed in out, and the number indicates which argument
// to use. Most of .NET formatting works like this.
Console.WriteLine("Your BMI is: {0}", BMI);
}
And additional strategy is to use the $"" string where you can do the following:
Console.WriteLine($"Your BMI is: {BMI}");

Categories

Resources