Hello guys I am a newbie and I am currently a first year in Computer Science. We have been given an exercise in which we have to convert from Fahrenheit to Celcius with methods (professor advised no static). We have started with C#. Here is my code.
namespace Week3_Exe3._1{
public class Formula
{
public double F;
public double C;
public void calculate(double F, double C)
{
C = (5 / 9) * (F - 32);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
F = double.Parse(Console.ReadLine());
Formula form = new Formula();
Console.WriteLine(F + "Fahrenheit correspond to " + form.calculate() + "Degrees celcius");
}
}
}
I am currently working with Visual Studio Community 2015 and in form.calculate, it reds out the calculate with the error
CS7036 C# There is no argument given that corresponds to the required
formal parameter '' of 'Formula.calculate(double, double)'
I searched for it but I still do not understand what is missing. I created an instance to use, but it's not working. Can anyone give me answer?
Your calculate method expect 2 parameters but you try to call it without parameters. In my humble opinion, it shouldn't take two parameters at all. Just one fahrenheit parameter is enough so it can calculate celsius value.
Also 5 / 9 performs an integer division —it always discards the fractional part— so it will always return 0.
A static method should be enough for your case;
static double Celsius(double f)
{
return 5.0/9.0 * (f - 32);
}
There a few errors in your code. First of all, your function only requires one input parameter, the temperature in Fahrenheit. After you have resolved this, you will find temperature of 100 Fahrenheit will return a temperature of 0 Celcius and this is obviously not correct. You need to modify your equation to use at least one fractional part otherwise C# will implicitly cast the values to integers.
using System;
namespace Week3_Exe3._1
{
public class Formula
{
public double calculate(double F)
{
return (5.0 / 9.0) * (F - 32.0);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
var F = double.Parse(Console.ReadLine());
Formula form = new Formula();
Console.WriteLine(F + " Fahrenheit correspond to " + form.calculate(F) + " Degrees celcius");
}
}
}
Your code has a few holes, my suggested rewrite is this:
public class Formula
{
public double F;
public double C;
public void calculate()
{
C = (5.0 / 9.0) * (F - 32);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
Formula form = new Formula();
form.F = double.Parse(Console.ReadLine());
form.calculate();
Console.WriteLine(F + "Fahrenheit correspond to " + form.C + "Degrees celcius");
}
}
keep in mind that this code only works for F => C, not the other way around.
The right answer is not going to be much use to you unless you understand what parameters and return values are and how to use them.
In your definition of the calculate method
public void calculate(double F, double C)
the method is expecting two input parameters, F and C. This means when you call the method from your main method, you need to pass in two values between the parentheses:
form.calculate(F, C)
As others have pointed out, you really only need one parameter, for the Farenheight. Which brings us to the next bit - how do you get a value back for C? This is what return values are for. That little word in between public and calculate defines the return type for your method. void means nothing is returned. In your case you'll be wanting to return a double. So putting this together the method definition should look like this
public double calculate(double F)
Finally you must actually return the value at the end of your method:
double C = (5.0 / 9.0) * (F - 32);
return C;
As you already assign the value of C you can remove C parameter from your function defenition code. Than your function must be like.
public void calculate(double F)
{
C = (5.0 / 9.0) * (F - 32.0);
}
Than in your code
public class Formula
{
// public double F; remove because F is used as parameter
public double C;
public void calculate(double F)
{
C = (5.0 / 9.0) * (F - 32.0);
}
public static void Main(string[] args)
{
Console.WriteLine("Please enter the Fahrenheit you wish to convert");
var F = double.Parse(Console.ReadLine()); // Creating new variable
Formula form = new Formula();
form.calculate(F); // Pass parameter to our function
Console.WriteLine(F + "Fahrenheit correspond to " + form.C /* retrive the results of calculation */ + "Degrees celcius");
}
}
Related
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
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();
}
}
This code below grabs 3 inputs from the console and then parses the numbers, after it then gets sent to getRealRoots method. which finds whether it has 2, 1 or no roots. The out parameters in the getrealroots are showing the following error:
The out parameter 'r1' must be assigned to before control leaves the
current method
The out parameter 'r2' must be assigned to before control leaves the current method
using System;
namespace Quadratic
{
public class Program
{
static public void Main(string[] args)
{
Console.WriteLine("Enter three numbers, (A,B,C)");
Double? a = GetDouble();
Double? b = GetDouble();
Double? c = GetDouble();
getRealRoots(a, b, c,out r1,out r2);
//throw new NotImplementedException("implement main");
}
static public int getRealRoots(double A, double B, double C, out double? r1, out double? r2)
{
double discriminant = B * B - 4 * A * C;
if (discriminant > 0)
{
r1 = (-B + Math.Sqrt(discriminant)) / (2 * A);
r2 = (-B - Math.Sqrt(discriminant)) / (2 * A);
Console.WriteLine("The equation " + GetQuadraticString(A, B, C) + " has two real roots:" + r1 + " " + r2);
}
else if (discriminant == 0)
{
r1 = -B / (2 * A);
Console.WriteLine("The equation " + GetQuadraticString(A, B, C) + " has one real root:" + r1);
}
else
{
Console.WriteLine("The equation " + GetQuadraticString(A, B, C) + " has no real roots:");
}
}
//throw new NotImplementedException("write a method that uses out variables to return the real discriminants of a quadratic");
}
}
First, you have the return type int, but do not return an int.
Second, the error message says that you have to assign your out parameters some value no matter what path of execution your method takes. You could solve this by assigning them some "default" values at the beginning of the method. Maybe like this?:
r1 = default (double);
r2 = null;
Hope I could help
As per the documentation on the out parameter modifier:
Variables passed as out arguments do not have to be initialized before being passed in a method call. However, the called method is required to assign a value before the method returns.
In the case of your provided code, in the method getRealRoots, you are:
Setting the out value of r1 and r2 where discriminant > 0
Setting the out value of r1 where discriminant == 0, but not the value of r2
Not setting r1, or r2 where none of the above conditions are met.
As the called method is required to assign a value, you must set the value of r1 and r2 in each execution pathway.
As you have defined the values as a nullable type, you can begin your method with some default values to resolve your issue:
static public int getRealRoots(double A, double B, double C, out double? r1, out double? r2)
{
r1 = null;
r2 = null;
// ... your method code
}
The default values are then overwritten under the specific IF conditions you have set.
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}");
public static void AddCharToNum <I> (ref I OriginalNumber, char NumberToAdd_Char) where I : struct {
double NumberToAdd = char.GetNumericValue (NumberToAdd_Char);
OriginalNumber = OriginalNumber * 10 + (int) NumberToAdd;
}
It displays this error: Operator *' cannot be applied to operands of typeI' and `int'
EDIT: The problem I'm trying to solve is this:
I don't want to repeat this code again and again:
switch (ParseState) {
case 1:
{
a = (a * 10) + char.GetNumericValue (NumberToAdd_Char);
}
case 2:
{
x = (x * 10) + char.GetNumericValue (NumberToAdd_Char); //where x is a float
}
case 3:
{
b = (b * 10) + char.GetNumericValue (NumberToAdd_Char); //where b is a double
}
case 4:
{
c = (c * 10) + char.GetNumericValue (NumberToAdd_Char); //where c is an integer
}
}
Since you are adding float number to the result anyway you might as well just use float or double variables. Also, it seems that your method logically returns number with additional character while having void return type. I would rewrite your method as follows:
public static double AddCharToNum (double originalNumber, char charToAdd) {
double numberToAdd = char.GetNumericValue(charToAdd);
return originalNumber * 10 + numberToAdd;
}
It seems to me that you are trying to parse some string of digits into integer digit by digit, I'm right?
If that is the case simply use int.Parse or int.TryParse
Enjoy
I guess you are using custom classes, which provice a numeric value. If so, you should make use of operator overloading.
C# allows user-defined types to overload operators by defining static member functions using the operator keyword
Check this page for more informations: MSDN: Overloadable Operators (C# Programming Guide)
Here is a quick example:
public static I operator *(I first, int second)
{
/* Pseudo code:
var number = first.Value;
I outVal = new I();
outVal.Value = number * second;
return outVal;
*/
}
Edit:
When using these operators on different/generic types like "I" is. Make a variable dynamic before using operators.
Like this:
dynamic dynOriginalNumber = OriginalNumber;
OriginalNumber = (OriginalNumber)(dynOriginalNumber * 10 + (float) NumberToAdd);