(C# Visual Studio 2019) Hello, my professor wants us to do the following code shown in the picture :
https://i.stack.imgur.com/ONNSV.png
We are fairly new into the course and have have talked about only a few of conversion methods.
Here is my attempt, but with an error that I cannot seem to wrap my head around. If someone can help me out or provide a solution, thanks!
Console.Write("Enter degrees Fahrenheit to convert to Celsius OR \nenter degrees Celsius
to convert to Fahrenheit.");
Console.Write("\n\nCurrent temperature scale (C for Celsius; F for Fahrenheit): ");
double tempscale = Convert.ToDouble(Console.ReadLine());
Console.Write("Current degrees: ");
double currentdeg = Convert.ToDouble(Console.ReadLine());
double degreeCelsius = 5 / 9 * (tempscale - 32);
double degreeFahrenheit = 9 / 5 * (degreeCelsius + 32);
if (tempscale == degreeFahrenheit)
Console.Write(degreeFahrenheit + "degrees Fahrenheit is" + degreeCelsius + "degrees Celsius");
if (tempscale == degreeCelsius)
Console.Write(degreeCelsius + "degrees Celsius is" + degreeFahrenheit + "degrees Fahrenheit");
Console.Write("\n\nPress any key to continue...");
Console.ReadKey();
if you write 5 / 9 in your code, you are doing integer division which is a little different from what you expect:
int x = 5;
int y = 9;
int result = x / y; // result is 0
if you divide 2 integers the result is an integer and for integer division that results in a fraction the result is rounded towards zero (everything after the decimal sign is discarded)
try writing floating point literals either as 5f for a float or 5d for a double...
5d / 9d should do what you expected
Your first goal is to get C/F from user. Let's make simple method for it. It will return C or F, based on user input.
Or you could use enum.
enum TemperatureScales { Celsius, Fahrenheit }
Here is sample of method to get temperature scale.
private static char GetTemperatureScale()
{
// Will wait for correct input from user
while (true)
{
Console.WriteLine("Enter C or F");
var input = Console.ReadLine();
if (input == "C" || input == "F") // you could improve and check for 'c' and 'f'
{
return input[0]; // you could use enum here if you are familiar with it
}
}
}
Use it in your code to ensure valid input.
Related
This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
How can I divide two integers to get a double?
(9 answers)
Closed 4 months ago.
I am new to coding in general, and especially new to C#. I am trying to write a program that asks the user if they want to convert a temperature to Fahrenheit or Celsius. The issue is, the math isn't checking out
This is what I have so far, and from what I know, it should work:
//declare variables
double temp = 0;
double newTemp = 0;
string? cf = "";
//ask if they want to covert to celcius or farenheit
Console.WriteLine("What are you converting to? Enter c for celsius or f for farenheit:");
cf = Console.ReadLine();
//if statement and output
if(cf == "c")
{
Console.WriteLine("Converting to Celsius. Enter temperature in farenheit:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = (temp - 32) * (5/9);
Console.WriteLine("Your temperature in celcius is " + newTemp + " degrees celsius.");
}
else if(cf == "C")
{
Console.WriteLine("Converting to Celsius. Enter temperature in farenheit:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = ((temp - 32) * (5/9));
Console.WriteLine("Your temperature in celcius is " + newTemp + " degrees celsius.");
}
else if(cf == "f")
{
Console.WriteLine("Converting to Farenheit. Enter temperature in celsius:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = (temp * (9/5) + 32);
Console.WriteLine("Your temperature in farenheit is " + newTemp + " degrees farenheit.");
}
else if(cf == "F")
{
Console.WriteLine("Converting to Farenheit. Enter temperature in celsius:");
temp = Convert.ToDouble(Console.ReadLine());
newTemp = (temp * (9/5) + 32);
Console.WriteLine("Your temperature in farenheit is " + newTemp + " degrees farenheit.");
}
else
{
Console.WriteLine("That is not celcius or farenheit. Please enter either c or f next time.");
Environment.Exit(0);
}
For some reason that I cant figure out, the math is always wrong. -40 degrees is never equal to -40 degrees in the inverse temperature, meaning that the math is incorrect. Would anyone be able to explain to me, in beginners terms, what the issue is and how I might resolve it?
P.S. - in many forums I looked at first, they used a term called floating-point that I don't really understand. If you use this in your answer, I would really appreciate an explanation on what it means.
Calculation the division 9/5 will treat both values as integer. This means the result is another integer which is 1 in this case.
To ensure the calculation is done like expected at least on of the numbers needs to be a double like 9.0/5. This results in the expected value of 1.8.
See this question for more details about this.
Another hint: You do not need to copy the whole code for lower and upper case input like
if (cf == "f")
{
//Code
}
else if (cf == "F")
{
//The same code
}
Just simply could make use of the or operator like
if (cf == "f" || cf == "F")
or use to lower
if (cf.ToLower() == "f")
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);
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")
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();
}
I'm coding a calculator in C#.
textBoxResult is a text box where I display the number
recount is the function which takes the angle in degrees and returns in radians
I take the angle from texBoxInput
public double recount(int number)
{
double wyjscie = 0.0;
double Number = number;
wyjscie = Number * (Math.PI / 180);
return wyjscie;
}
//function which is called out when user presses the button:
textBoxResult.Text = Math.Round(Math.Tan(recount(Convert.ToInt32(texBoxInput.Text))),2).ToString();
As you can see I was trying to round this number when using Math.Tan, but still Math.Tan gives me that tan from 90 degrees is 1,63317787283838E+16 .
I have been trying to find the answer but failed. I can't figure it out how to display correct result.
Basically, it looks like this is expected behavior from Math.Tan. I don't know other languages very well, so I'm not sure if this is normal for floating point Math or specific to the C# implementation. (NOTE: Afterwards, I found that Google's online calculator returns the same suggesting it expected behavior for floating point trig functions, probably related to the fact that pi is irrational and the limitations of the double precision data type)
However, working backwards from this result I am seeing that Math.Atan(// your result); and Math.Atan(double.PositiveInfinity) both return 90 degrees, suggesting this is expected?
Here's my test:
var deg = 90.0;
var rads = deg * (Math.PI / 180);
var result = Math.Tan(rads);
if (Double.IsInfinity(result))
Console.WriteLine("Tan of 90 degrees is Infinity");
else if (Double.IsNaN(result))
Console.WriteLine("Tan of 90 degrees is Undefined");
else
Console.WriteLine("Tan of 90 degrees is {0}", result);
Console.WriteLine("Arc Tan of {0} is {1} degrees", double.PositiveInfinity, Math.Atan(double.PositiveInfinity) * 180 / Math.PI);
Console.WriteLine("Arc Tan of {0} is {1} degrees", result, Math.Atan(result) * 180 / Math.PI);
Which gives the output of:
Tan of 90 degrees is 1.63317787283838E+16
Arc Tan of Infinity is 90 degrees
Arc Tan of 1.63317787283838E+16 is 90 degrees
So my guess is unless someone can come in and provide a workaround, you might have to program around this as an edge case to get the correct result.
The "correct result" for any of the trig functions will be limited to the precision of double, which is 15 significant figures, so if you need more than that, you will need to find a library that supports more precise mathematics.
Since Math.Tan(Math.PI/2) seems to provide an undesirable response you could do something like this:
public double ComputeTangent(double angleRads)
{
if (angleRads == Math.PI/2)
return double.PositiveInfinity
if (angleRads == - Math.PI/2)
return double.NegativeInfinity
return Math.Tan(angleRads);
}
Round is doing exactly what it says on the tin:
The maximum total number of integral and fractional digits that can be
returned is 15. If the rounded value contains more than 15 digits, the
15 most significant digits are returned. If the rounded value contains
15 or fewer digits, the integral digits and as many fractional digits
as the digits parameter specifies are returned.
1.63317787283838E+16 are the 15 most significant digits, and there is no fractional part.
If you want to display this as 1,63E+016 you can use:
number.ToString('E2', CultureInfo.CreateSpecificCulture("fr-FR"))
(Or any other locale that uses , as the decimal separator )
See: The Exponential ("E") Format Specifier
using System;
namespace Lab_Ex_12
{
class SimpleCalculator
{
double num1, num2;
public void read()
{
Console.WriteLine("\n Enter any two numbers:");
Console.Write("\n Number1 : ");
num1 = double.Parse(Console.ReadLine());
Console.Write("\n Number2 : ");
num2 = double.Parse(Console.ReadLine());
}
public void add()
{
double sum = num1 + num2;
Console.WriteLine("\n Result : ({0}) + ({1}) = {2}", num1, num2, sum);
}
public void subtract()
{
double diff = num1 - num2;
Console.WriteLine("\n Result : ({0}) - ({1}) = {2}", num1, num2, diff);
}
public void multiply()
{
double prod = num1 * num2;
Console.WriteLine("\n Result : ({0}) X ({1}) = {2}", num1, num2, prod);
}
public void divide()
{
double qt = num1 / num2;
Console.WriteLine("\n Result : ({0}) / ({1}) = {2}", num1, num2, qt);
}
}
class ArithmeticOperations
{
public static void Main()
{
SimpleCalculator SC = new SimpleCalculator();
int ch, i=1;
while(i==1)
{
Console.Clear();
Console.WriteLine("\n *************************");
Console.WriteLine("\n ZAHID SIMPLE CALCULATOR.");
Console.WriteLine("\n *************************");
Console.WriteLine("\n 1-----> ADDITION");
Console.WriteLine("\n 2-----> SUBTRACTION");
Console.WriteLine("\n 3-----> MULTIPLICATION");
Console.WriteLine("\n 4-----> DIVISION");
Console.WriteLine("\n 5-----> EXIT");
Console.WriteLine("\n *************************");
Console.Write("\n\n Enter your choice: ");
ch = int.Parse(Console.ReadLine());
switch (ch)
{
case 1: SC.read();
SC.add();
break;
case 2: SC.read();
SC.subtract();
break;
case 3: SC.read();
SC.multiply();
break;
case 4: SC.read();
SC.divide();
break;
case 5: Environment.Exit(-1);
break;
default: Console.WriteLine(" Sorry !!! Wrong choice.");
break;
}
Console.Write("\n Press ENTER to Continue. ");
Console.ReadLine();
}
Console.WriteLine("\n Cannot continue... Bye");
}
}
}