How do i invoke a method in c#? - 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);

Related

How to round to the nearest thousandth using 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

If an user does not input a local variable how do i define it using other variables? C#

Let me explain.
I am a high school student with not a lot of expirience programming in C#, we have an asigment to make a geometry calculator i got a triangular pyramid, but thats beside the point. The calculator is suposed to get an imput from the user and then with that given data calculate the surface and the volume.
double a = Convert.ToDouble(Console.ReadLine());
double h = Convert.ToDouble(Console.ReadLine());
double H = Convert.ToDouble(Console.ReadLine());
double area = Math.Pow(a, 2) * Math.Sqrt(3) / 4 + 3 * a * h / 2;
double volume = Math.Pow(a, 2) * Math.Sqrt(3) * H / 12;
Console.WriteLine(volume);
Console.WriteLine(area);
Console.ReadLine();
Now thats easy for me , but a problem arises when the user does not know the value of one of the variables for example the hight.In such a instance the calculator is suposed to calculate it using the other two local variables.
double h = Convert.ToDouble(Console.ReadLine());
double h = Math.Sqrt(Math.Pow(a * Math.Sqrt(3) / 3, 2) + Math.Pow(H));
I know i know you cant do this but i coudn't find anything on the internet, so i beg you for help since this is 20% of my grade.
And if this can't be done do you have any other sugestions.
P.s. Sorry if my english is bad.
This is fairly simple to accomplish. Not having a variable means that you'll have a different formula/calculation depending on the missing variable, you can do this with if conditionals.
//Read them in as strings if you want to check if they're "_blank_", convert them
later.
string a = Console.ReadLine();
string h = Console.ReadLine();
string H = Console.ReadLine();
double area = 0;
double volume = 0;
if(a == "") //If it's blank, no entry do this code.
{
//This is how I'd convert it, just a little less pretty for the sake
//of understanding for you. You'd need to do this in every if block.
double returnedDoubleh = ConvertToDouble(h);
double returnedDoubleH = ConvertToDouble(H);
//Have your formula if `a` is blank.
}
else if (h == "")
{
double returnedDoubleA = ConvertToDouble(a);
double returnedDoubleH = ConvertToDouble(H);
//Have your formula if `h` is blank.
}
else if (H == "")
{
double returnedDoubleA = ConvertToDouble(a);
double returnedDoubleh = ConvertToDouble(h);
//Have your formula if `H` is blank.
}
else //This is if none are blank OR More than one is blank which would crash if
more than one is blank..
{
area = Math.Pow(a, 2) * Math.Sqrt(3) / 4 + 3 * a * h / 2;
volume = Math.Pow(a, 2) * Math.Sqrt(3) * H / 12;
}
Console.WriteLine(volume);
Console.WriteLine(area);
Console.ReadLine();
Example Function to convert your string values.
public static double ConvertToDouble(string nonConverted)
{
double converted;
while (!double.TryParse(nonConverted, out converted) || String.IsNullOrWhiteSpace(nonConverted))
{
Console.Clear();
Console.WriteLine($"INVALID RESPONSE\n\r" +
$"\n\rTry Again");
nonConverted = Console.ReadLine();
}
return converted;
}
In your conditionals you can also use a "Variable" so instead of saying if(a == "") you could do something like if(a == "x")

Input String was not in correct format || ConsoleApp

Basically I'm trying to not let the user input string instead of an integer; but on line of code:
else if (Convert.ToString(result) == "")
I get an error.
Full code:
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result = Convert.ToInt32(Console.ReadLine());
if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else if (Convert.ToString(result) == "")
{
Console.Write("Error, you can not convert a text");
}
else
{
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}
The safest way to get a number from a string is to use the TryParse method, because this method returns two values! The actual return type is a bool which indicates whether or not the string was successfully converted, and the other is an out parameter, which is of the type that we're converting to, and which gets set to the converted value (or is set to the default value of the type if the conversion fails).
For temperatures, we often deal with decimal numbers, so a double is probably a good type to store the result. So, we'll use double.TryParse.
Now, since we don't necessarily want to just quit if the user makes a mistake, we should probably do our conversion in a loop, so if it fails, we just ask the user to try again. And since this code will be used in other places as well, we can make a helper method that takes in a prompt that we display to the user, and returns the strongly-typed user response:
private static double GetDoubleFromUser(string prompt = null)
{
double result;
do
{
Console.Write(prompt);
} while (!double.TryParse(Console.ReadLine(), out result));
return result;
}
With this method, we can now just declare a double and assign it to the return value of the method above, like:
double userInput = GetDoubleFromUser("Enter a temperature: ");
Another thing we can correct in the code are the formulas used to do the conversions. A quick check online shows us that we add a number for kelvin and we do multiplication, division, and addition for Fahrenheit. We can calculate these values on the fly once we have the Celsius temperature from the user:
private static void Main()
{
double celcius = GetDoubleFromUser("Enter a Celcius temperature: ");
double fahrenheit = celcius * 9 / 5 + 32;
double kelvin = celcius + 273.15;
Console.WriteLine("Kelvin = " + kelvin);
Console.WriteLine("Fahrenheit = " + fahrenheit);
GetKeyFromUser("Done! Press any key to exit...");
}
Output
Convert.ToInt32 throws an exception if the input string is not a number. To fix that, you can use int.TryParse instead.
Example:
using System;
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
int calcKelvin = 273;
int calcFahren = 32;
int result;
bool isNum=int.TryParse(Console.ReadLine(),out result);
if (!isNum)
{
Console.Write("Error, you can not convert a text");
}
else if (result == 0)
{
Console.WriteLine("Check it up on google!");
Console.Title = "I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT || I'M USELESS CONSOLE, YOU CAN NOW EXIT ||";
}
else {
Console.WriteLine("Kelvin = " + calcKelvin * result);
Console.WriteLine("Fahrenheit = " + calcFahren * result);
}
}
}

calculating huge numbers in C#

i have a problem the product of multiplying three numbers in my program, Even after BigInteger type.
I don't get any meaningful number.
Please check the code below:
using System;
using System.Numerics;
class Program
{
static void Main()
{
denss:
string density;
int den;
Console.WriteLine("Please enter the density value in kg/m3");
density = Console.ReadLine();
bool dens = int.TryParse(density, out den);
if (dens == false)
{
Console.WriteLine("Please enter numbers only");
goto denss;
}
Console.WriteLine(den);
velss:
string velocity;
int vel;
Console.WriteLine("Please enter the velocity value in m/s");
velocity = Console.ReadLine();
bool vels = int.TryParse(velocity, out vel);
if (vels == false)
{
Console.WriteLine("Please enter numbers only");
goto velss;
}
Console.WriteLine(vel);
lengt:
string length;
int len;
Console.WriteLine("Please enter the length value in m");
length = Console.ReadLine();
bool leng = int.TryParse(length, out len);
if (leng == false)
{
Console.WriteLine("Please enter numbers only");
goto lengt;
}
Console.WriteLine(len);
BigInteger rel = den * vel * len;
Console.WriteLine(rel);
if (rel>100000)
Console.WriteLine("turbuelent flow. Reynolds no is ", rel);
else
Console.WriteLine("laminar flow. Reynolds no is ", rel);
Console.ReadKey();
}
}
The output i get is shown in this photo:enter image description here
Amongst other issues, your main problem is the following line:
BigInteger rel = den * vel * len;
What is happening here is den * vel * len is calculated as an int because all values involved are int. This int overflows and is meaningless. This meaningless number is then assigned to the BigInteger rel. What you need is:
BigInteger rel = new BigInteger(den) * new BigInteger(vel) * new BigInteger(len);
or declare them as double, which is what they should have been for this problem domain in the first place.
The code should be
if (rel>100000)
Console.WriteLine("turbuelent flow. Reynolds no is {0}", rel);
else
Console.WriteLine("laminar flow. Reynolds no is {0}", rel);
And please, don't use gotos
You aren't actually outputting the value on the console. The string that you use as the output (the first parameter to WriteLine) must contain a token showing where to insert the second parameter (the number) into the string. For example:
Console.WriteLine("turbuelent flow. Reynolds no is {0}", rel);
The {0} shows where the parameter should go. If you have multiple parameters to output, you can use {0}, {1}, and so on.
Actually, your code could be written a bit less repetitively like this:
string flowType = "";
if (rel > 100000) flowType = "turbulent";
else flowType = "laminar";
Console.WriteLine("{0} flow. Reynolds no is {1}", flowType, rel);
See https://msdn.microsoft.com/en-us/library/586y06yf(v=vs.110).aspx for more details.
Too many problems:
incorrect output Console.WriteLine("turbuelent flow. Reynolds no is ", rel); - {0} omitted
BigInteger rel = den * vel * len; prone to integer overflow
wrong types - why den, vel, len are integers? Why, say, len can't be 15 cm = 0.15 meters?
goto...
copy/paste
Let's do it right. First of all, decompose your solution, extract a method, do not copy/paste:
//DONE: double, not int - velocity, density and length are not necessary integers
private static double ReadValue(string title) {
double result = 0.0;
Console.WriteLine(title);
while (!double.TryParse(Console.ReadLine(), out result))
Console.WriteLine("Please enter numbers only");
return result;
}
Then implement a simple Main() without goto and other ugly things
static void Main() {
//DONE: double, not int:
// what if alcohol travels along a pipe:
// density = 856.96 kg/m3 (some reference value)
// velocity = 3.6 m/s (5 km/h)
// length (diameter?) = 0.015 m (1.5 cm)
double den = ReadValue("Please enter the density value in kg/m3");
double vel = ReadValue("Please enter the velocity value in m/s");
double len = ReadValue("Please enter the length value in m");
double rel = den * vel * len;
//DONE: use formatting not a complex logic
// F0 - we don't want anything after the decimal point, as if rel is integer
Console.WriteLine("{0} flow. Reynolds no is {1:F0}", // string
rel > 100000 ? "turbuelent" : "laminar", // 1st arg
rel); // 2nd arg
Console.ReadKey();
}

Validating multiple user input in console application

I'm pretty new to C# and am wondering how I'd go about validating user input to meet the following requirements:
has to be a decimal type. if it isn't it should ask the user to enter a decimal value. (Which i believe i have covered in my code below)
also has to be within a specific range (1 - 1,000,000). If it isn't it should ask the user to enter a number within the correct range
What's the most efficient way of doing this considering i will have multiple user input to validate in the same sort of way.
decimal balance;
Console.Write("Starting Balance: $");
while (!decimal.TryParse(Console.ReadLine(), out balance))
{
Console.Write("Please enter a valid decimal value: $");
}
EDITED BELOW
How about this?
decimal balance;
Console.Write("Starting Balance: $");
while(true)
{
if (!decimal.TryParse(Console.ReadLine(), out balance))
Console.Write("Please enter a valid decimal value: $");
else if (balance < 1 || balance > 100)
Console.Write("Please enter an amount between 1 and 100: ");
else
break;
}
Console.WriteLine("Balance entered is: " + balance.ToString("n"));
return val; line gave me an error so i left it out but the above seems to work?
I'd try something like:
decimal GetUserInput(string inputQuery, decimal min, decimal max)
{
Console.Write(inputQuery);
decimal val;
while(true)
{
if(!decimal.TryParse(Console.ReadLine(), out val))
Console.Write("Please enter a valid decimal value: $");
else if(val < min || val > max)
Console.Write("Please enter an amount between " + min + " and " + max + ": $");
else // the value is a decimal AND it's correct
break;
}
return val;
}
Then use it like:
var startingBalance = GetUserInput("Starting Balance: $", 1, 100000);
var endingBalance = GetUserInput("Ending Balance: $", 1, 100000);
//...
If your min and max are fixed, then you could not pass them as arguments and use a fixed check. And you could also avoid having the query : $ passed in if needed, but I'll leave that to you
Update
The reason why the return val line was giving you an error was because you were inlining it (probably in a void returning function). What I was doing was making a function since you specified it needed to be reusable.
So in your program, you need to make a separate function... your program would look something like this:
class Program
{
// We're declaring this function static so you can use it without an instance of the class
// This is a function, so it can be called multiple times, with different arguments
static decimal GetUserInput(string inputQuery, decimal min, decimal max)
{
// Write the argument "inputQuery" to console
Console.Write(inputQuery);
decimal val;
// Loop indefinitely
while(true)
{
// Read from console into a decimal "val"
if(!decimal.TryParse(Console.ReadLine(), out val))
// It was not a correct decimal, so write the prompt
Console.Write("Please enter a valid decimal value: $");
// It was a correct decimal
else if(val < min || val > max)
// But not in range, so write a different prompt
Console.Write("Please enter an amount between " + min + " and " + max + ": $");
// It was a decimal and within range
else
// so we break the infinite loop and exit after the "}"
break;
// If we have got to this point (we didn't hit the "break"),
// it was either not a decimal or it wasn't within range,
// so it'll loop again and ask for a value from console again.
// The prompt was already written above (in the "ifs")
}
// We got out of the while(true){} loop, so it means we hit "break"
// above, and that means "val" contains a correct value (decimal and
// within range), so we return it to the caller
return val;
}
static void Main()
{
// Your original code went here, but see how my function is *outside* function Main()
// You use my function (GetUserInput) here:
var startingBalance = GetUserInput("Starting Balance: $", 1, 100000);
var endingBalance = GetUserInput("Ending Balance: $", 1, 100000);
// Then with the returned values (stored in "startingBalance"
// and "endBalance"), you can do what you want:
Console.WriteLine("Starting balance was: " + startingBalance.ToString("n"));
}
}
I've made a fiddle with the whole program so you can test online and make changes: https://dotnetfiddle.net/HiwwIP
If I were you, I would do such:
bool isInvalid, isOutOfRange;
decimal balance = 0;
isOutOfRange = true;
do
{
string input = Console.ReadLine();
isInvalid = !Decimal.TryParse(input, out balance);
if (!isInvalid)
{
// use balance<=1 if 1 should not be included
// use balance>=1000000 if 1000000 should not be included
isOutOfRange = (balance < 1 || balance > 1000000);
}
if (isInvalid)
{
Console.WriteLine("Please enter a valid decimal value: $");
}
else if (isOutOfRange)
{
Console.WriteLine("Please enter value between 1 and 1000000: $");
}
} while (isInvalid || isOutOfRange);
Console.WriteLine("{0}, That is a valid value!", balance.ToString());
Console.ReadKey();
Of course you can shortcut by eliminating bool definitions and directly calling functions instead; but I wrote in detail for clarity as you indicated that you are "pretty new".

Categories

Resources