Getting Error while using Math.Sqrt function in C# - c#

In the program given below, Math.Sqrt function is throwing an error that is
"Expression denotes a variable', where amethod group' was expected."
What seems to be problematic here?
using System;
class program{
static void Main(){
Console.WriteLine("Enter the sides(a,b,c) of a triangle :");
int a = Convert.ToInt16(Console.ReadLine());
int b = Convert.ToInt16(Console.ReadLine());
int c = Convert.ToInt16(Console.ReadLine());
double s = (a+b+c)/2;
double area = Math.Sqrt(s(s-a)(s-b)(s-c));
if (a==b&&b==c){
Console.WriteLine("This is an Equilateral trangle");
}
else if(a==b&&b!=c||a!=b&&b==c){
Console.WriteLine("This is an Isosceles trangle");
}
else{
Console.WriteLine("This is an Scalene trangle");
}
}
}here

C# will not assume a multiplication in the same way you write down an equation, and instead will see s(s-a) as a function called s that takes a parameter of s-a. You need to explicitly state the multiplication sign:
double area = Math.Sqrt(s*(s-a)*(s-b)*(s-c));

Related

The name 'userAge' does not exist in this context

Im creating a simple calculation program as i am learning C#. I do not understand how to make a user input an Integer when you cannot convert a string into an Int. I am using 'Int.Parse' to assign the input as an integer but it the console says that userAge does not exist in this context.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PlanetCalculations {
class Program
{
static void Main(string[] args)
{
// Your Age
Console.WriteLine("Enter Your Age:");
userAge = int.Parse(Console.ReadLine());
Console.WriteLine(userAge);
// Length of years on Jupiter (in Earth years)
double jupiterYears = 11.86;
// Age on Jupiter
// Time to Jupiter
// New Age on Earth
// New Age on Jupiter
// Log calculations to console
}
}
}
Instead of
userAge = int.Parse(Console.ReadLine());
use
int userAge = int.Parse(Console.ReadLine());
With int in front of userAge, you define the variable. Without int the program does not know a variable named userAge.
Also, consider using TryParse instead of int.Parse like this:
string userInput = Console.ReadLine();
bool isValidInt = int.TryParse(userInput, out int userAge);
if (!isValidInt)
{
//False user input...
Console.WriteLine($"Input '{userInput}' is not an integer. Exiting program ...")
return;
}
From what I see you have never defined that variable. Place var before it and it should work.
Personally, in your case, I would use TryParse() instead of Parse(). With Parse() if the user enters a value that can not be converted to a string, it will throw an error. It would look like this:
Console.WriteLine("Enter Your Age:");
int userAge;
if (!int.TryParse(Console.ReadLine(), out userAge));
{
Console.Write("Please enter a valid number.");
}
TryParse() returns true if the conversion worked. If it fails, it returns false. And if the conversion worked, then userAge will contain the numeric value that was entered.

C# returning a completely unrelated and seemingly random integer?

I am currently a complete beginner to C# however I am having this issue and as a python user the error doesn't make any sense to me. I have tried to find a fix but I don't know what to search for or how to describe the error, so please help!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace testin
{
class Program
{
static void Main(string[] args)
{
PrintState();
CalculateAge();
EzMaths();
//Here I call the procedure which is declared later on
Console.ReadLine();
}
static void PrintState()
{
/*Here I write the procedure of 'PrintState',
* or print statement. The program will print "hey world"
* to the console as a result. */
Console.WriteLine("Hey world");
}
static void EzMaths()
{
Console.WriteLine("Enter the first number ");
Console.Write("> ");
int num1 = Console.Read();
Console.WriteLine("Enter the second number ");
Console.Write("> ");
int num2 = Console.Read();
int total = (num1 + num2);
Console.WriteLine(total);
}
static void CalculateAge()
{
Console.WriteLine("Enter your year of birth ");
Console.Write("> ");
int date = Console.Read();
int age = (2018 - date);
Console.Write("You are " + (age));
Console.ReadLine();
}
}
}
Console.Read(); does read the next Character, but as its int representation. You'll need to use Console.ReadLine();, but now you're faced with a different problem, Console.ReadLine(); returns a string and not a int, so now you need to Convert it. In the .NET World you'd do it like this:
string userInput = Console.ReadLine();
int userInputNumber = Convert.ToInt32(userInput);
This is not safe, as the user could enter something that's not a number and that would make the program crash. Of course if you're just getting started and making a "Hello World" application this is probably not your biggest concern.
I'll post the better version anyways if yo're interested:
string userInput = Console.ReadLine();
int userInputNumber;
if (int.TryParse(userInput, out userInputNumber))
{
// Do code here with userInputNumber as your number
}
And in C# (like every modern Language) we have some Syntatic Sugar to make this shorter but also harder to read:
if (int.TryParse(Console.ReadLine(), out int userInputNumber))
{
//Do code here
}
you need to use console.ReadLine() instead of console.Read() in your CalculateAge function.
refer to this answer to understand the difference between Console.Read and console.ReadLine:
Difference between Console.Read() and Console.ReadLine()?
Yet I would suggest that you also add a tryParse in order to validate if the entered value is an integer before you convert it to int
something like this:
static void CalculateAge()
{
Console.WriteLine("Enter your year of birth ");
Console.Write("> ");
string input = Console.ReadLine();
int date = 2018;
Int32.TryParse(input, out date);
int age = (2018 - date);
Console.Write("You are " + (age));
Console.ReadLine();
}
you can have another implementation if you dont want it to have a default value of 2018. like add a while loop, while tryParse != false then keep asking for input.

C# Method Declaring

public void GetPosNonZeroDouble()
{
double x;
Console.WriteLine("Enter The Length Of The Side");
x = double.Parse(Console.ReadLine());
if (x <= 0)
Console.WriteLine("Error - input must be a non - zero positive number");
else
return x;
x = double.Parse(Console.ReadLine());
}
static void ProcessSquare()
{
GetPosNonZeroDouble();
double side;
double answer;
Console.WriteLine();
side = double.Parse(Console.ReadLine());
answer = Math.Pow(side, 2);
Console.WriteLine("The Square Area is {0}", answer);
}
I am supposed to have a "GetPosNonZeroDouble" which needs to act like this image: c#Question
I have declared this method but am unsure how I tell processSquare() to check if the number is < 0 and how to display such by inputing the module.
Please assist me with this as i am stuck finding the solution to my problem.
You need to either make the method static, or make it part of a class and call it from an instance of the class. Also, you can't return values from a void method.
public static double GetPosNonZeroDouble()
{
double x = 0;
while (x <= 0)
{
Console.WriteLine("Enter The Length Of The Side");
if (!double.TryParse(Console.ReadLine(), x) || x <= 0)
{
Console.WriteLine("Error - input must be a non - zero positive number");
}
}
return x;
}
GetPosNonZeroDouble
Is an instance method that you are trying to call from a static method and you can't do that. You need to create an instance of whatever class GetPosNonZeroDouble is in and then invoke it using the dot notation.
Have a look here and you should also try some C# tutorials to get you going.
It seems that you don't have experience with methods in general.
As a start, I would recommend you to check the official C# documentation for methods:
https://msdn.microsoft.com/en-us/library/vstudio/ms173114(v=vs.100).aspx
For example, your method GetPosNonZeroDouble() does not return anything but you try to return a value with return x; (which would end up in a compiler error).

Cannot implicitly convert type 'string' to 'int' (CS0029) [duplicate]

This question already has answers here:
Cannot implicitly convert type string to int
(4 answers)
Closed 8 years ago.
I'm on my way to learn C# by following the basic training tutorial from Lynda and trying to make some changes on their examples.
I'm stuck on an error that I can't find a solution for on Google.
Cannot implicitly convert type 'string' to 'int' (CS0029)
Code:
namespace l2
{
class Program
{
public static void Main(string[] args)
{
int arg;
arg = Console.ReadLine();
int result1;
result1 = formula(arg);
Console.WriteLine("the result is {0}",result1);
Console.ReadKey();
}
static int formula (int theVal){
return (theVal * 2 + 15);
}
}
}
I really don't understand why I get that error. My function is getting an int, the arg that I want to get from console is also an int. Where is the string that the compiler is talking about? :)
Console.ReadLine() returns a string.
What you want is
arg = int.Parse(Console.ReadLine());
The correct solution in this case will be.
string input;
input= Console.ReadLine();
int numberArg;
while (!int.TryParse(input, out numberArg))
{
Console.WriteLine(#"Wrong parameter. Type again.");
input= Console.ReadLine();
}
var result1 = formula(numberArg);
Console.WriteLine("the result is {0}", result1);
Console.ReadKey();
You could also attempt some subtle validation, by using the int.TryParse. Which will attempt to convert the value to an integer, if it indeed fails it will use the original value:
int id = 1;
int.TryParse("Hello", out id);
Console.WriteLine(id)
Output: 1
int id = 1;
int.TryParse("40", out id);
Console.WriteLine(id)
Output: 40
Also note that Console.ReadLine() will return a type of string. So to correctly solve your issue, you would do:
int arguement = 0;
while(!int.TryParse(Console.ReadLine(), out arguement)
{
Console.WriteLine(#"Error, invalid integer.");
Console.ReadLine();
}
So until they enter a valid integer they'll be trapped in the loop.

Invalid token errors with enums

I'm having a little trouble with this code that I'm writing for a simple program. I get tons of errors saying "invalid token".
The program basically asks for 2 integers and sums them up, but the program needs to be called in another method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AustinPDangeloJPA03
{
class Add
{
static void Main(string[] args)
{
double num1,
num2,
sum;
Console.Write("Enter the First integer: ");
num1 = int.Parse(Console.ReadLine());
//First Integer entered and storred
Console.Write("Enter the Second integer: ");
num2 = int.Parse(Console.ReadLine());
//Second Integer entered and storred
sum = Display(double a, double b);
//First and second numbers added together
Console.WriteLine(" {0} + {1} = {2} ",num1,num2,sum);
//displays the sum
//Instructs the user to press the Enter key to end the program
Console.WriteLine("Press the Enter key to terminate the program...");
Console.ReadLine();
}//Closes Main Method
static enum Display(a,b)
{
double c = a + b;
return c;
}//closes display method
}//Closes Class Add
}
This is not correct:
static enum Display(a,b)
{
double c = a + b;
return c;
}
The enum keyword is used to declare an enumeration. In order to define a method, you need a valid return type (such as int or double), and you need to provide the proper types for the individual arguments. You can optionally add static if you want it to be a static method, but that depends on its purpose.
I suspect you want to use something more like:
double Add(double a, double b)
{
// ...
If you then correct the line that called this method:
sum = Display(double a, double b);
This should compile and give you what you expect.
Your Display method is not declared correctly.
You need to declare a method that takes two numbers and returns a third number.
Consult your textbook and assignment for more information on how to declare a method and which types to use.
You're also not calling it correctly; method calls do not take types.
While it is not the source of your errors, it does indicate a misunderstanding of types:
double num1, num2,sum;
[...]
num1 = int.Parse(Console.ReadLine());
The first line declares some double variables.
The second line tries to parse int variables.
While the int will get auto-converted to a double, your code will be better if it is consistent with the use of types. You should switch to either int types, or to Double.Parse().
The enum keyword is for creating enumerations, for example:
public enum Color { Red, Green, Blue };
You have to specify a data type as return type for your Display method, and data types for the parameters:
static double Display(double a, double b) {
double c = a + b;
return c;
}
Also, you don't specify data types when you call the method, so change that to:
sum = Display(a, b);
Change this line to:
double sum = Display(num1, num2);
And change your Display method to be a method.
private static double Display(double a, double b)
{
double c = a + b;
return c;
}

Categories