This question already has answers here:
Divide by zero and no error? [duplicate]
(2 answers)
Why does this method return double.PositiveInfinity not DivideByZeroException?
(4 answers)
Inconsistency in divide-by-zero behavior between different value types
(5 answers)
Closed 2 years ago.
I have written the code below. And I want the output to be :Error!Division by zero..
But my output is: infinity.
What's the problem with this code?
//This is the class:
public class Exc
{
private double number1;
private double number2;
public double result;
public Exc(double n1,double n2)
{
this.number1 = n1;
this.number2 = n2;
}
public void Div(double number1, double number2)
{
try
{
result = number1 / number2;
Console.WriteLine(result);
}
catch (DivideByZeroException e)
{
Console.WriteLine("Error! Division by zero.{0}",e);
}
}
}
//This is my program:
static void Main(string[] args)
{
Console.WriteLine("Enter the first number:");
double n1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter the second number:");
double n2 = Convert.ToDouble(Console.ReadLine());
Exc obj = new Exc(n1, n2);
obj.Div(n1,n2);
Console.ReadKey();
}
Arithmetic operations with the float and double types never throw an exception. The result of arithmetic operations with those types can be one of special values that represent infinity and not-a-number:
double a = 1.0 / 0.0;
Console.WriteLine(a); // output: Infinity
Console.WriteLine(double.IsInfinity(a)); // output: True
Source
You are going to get divide by zero error only in case of integer input in c#. For double the desired output is infinity. You should put a check for Double.IsInfinity if you want to know if it is divided by zero.
Related
This question already has answers here:
Is there a string math evaluator in .NET?
(18 answers)
Closed 2 years ago.
Im trying to convert a string called symbol into an operator (+ = - /) for a calculator. Instead of having only one symbol that is already chosen before, the user will choose what symbol to use (the result wont work since its not an operator).
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
string symbol;
Console.WriteLine("Input a number");
num01=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Write the second number");
num02=Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Choose a mathematic symbol");
symbol=Convert.ToString(Console.ReadLine());
double result = ( num01 symbol num02 );
Console.WriteLine ("The result is " + result);
Console.ReadKey();
}
}
You should create an additional method that will take your symbol and integers and perform the necessary calculation.
private int Calculate(string operator, int number1, int number2)
{
if (operator == "+")
{
return number1 + number2;
}
else if (operator == "-")
{
return number1 - number2;
}
else if (operator == "*")
{
return number1 * number2;
}
else if (operator == "/")
{
return number1 / number2;
}
else
{
throw new ArgumentException("Unexpected operator string: " + operator);
}
}
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}");
I want to be able to use the "costOfCar" function in the "InterestPaid" function. I would appreciate any help.
namespace Functions9
{
class Program
{
static void Main(string[] args)
{
Double userCarCost, userDownPayment, userInterestRatePercentage, test; //declares "userCarCost" , "userDownPayment variable", "userInterestRatePercentage"
Console.WriteLine("This program will do some calculations for you about a car loan."); //explains the purpose and function of program to user
Console.WriteLine(); //adds an empty line
Console.WriteLine("What is the cost of your new car?"); //prompt user for input
userCarCost = Convert.ToDouble(Console.ReadLine()); //converts user input regarding car cost to double and stores in "userCarCost" variable
Console.WriteLine(); //adds an empty line
Console.WriteLine("How much money will you put as a down payment");
userDownPayment = Convert.ToDouble(Console.ReadLine()); //converts user input regarding down payment to double and stores in "userDownPayment" variable
Console.WriteLine();
Console.WriteLine("What is your interest rate percentage? Put a point before the number");
userInterestRatePercentage = Convert.ToDouble(Console.ReadLine()); //converts user input regarding interest rate to double and stores in "userInterestRatePercentage" variable
Console.WriteLine(); //adds an empty line
Console.WriteLine("How many years before you pay back the loan?");
CostOfCar(userCarCost, userDownPayment);
}
static double CostOfCar(double number1, double number2)
{
double costOfCar = number1 - number2; //"costOfCar" variable is determined by subtracting "userCarCost", "userDownPayment"
return costOfCar; // returns the cost of the car to the main method
}
static double InterestPaid(double number1, double number2)
{
double interestPaid = number1 * number2;
return interestPaid;
}
}
}
Just call it?
static double InterestPaid (double number1, double number2)
{
double interestPaid = number1 * number2 * CostOfCar(number1, number2);
return interestPaid;
}
Or with the correct formula you need.
(update according remark):
static double InterestPaid (double number1, double number2)
{
var costOfCar = CostOfCar(number1, number);
double interestPaid = number1 * number2 * costOfCar;
return interestPaid;
}
Btw, it is better to name functions with a verb, like CalculateCostOfCar.
You need something to capture the value.
In Main, instead of
CostOfCar(userCarCost, userDownPayment);
write
double cost = CostOfCar(userCarCost, userDownPayment);
Here, the variable cost is capturing the returned value from the function for later use.
static double InterestPaid (double number1, double number2)
{
var val=Program.CostOfCar(number1, number2);
double interestPaid = number1 * number2;
var total=val+interestpaid;
return total;
}
The application shall perform the selected menu math operation on the two entered numbers and display the answer.You must use methods for each math operation and a decision must be used to pick which method should be executed.
The application shall display an error message when a correct menu number is not entered. This is a decision where 1-5 are valid selections and everything else is “Invalid”.
The application shall not allow division by zero. Do not perform the divide operation if the second number variable is zero, but instead display an error message.
I have written the code but the program is showing the following error:
1. No overload for method AddNumber takes 0 arguments. this error is showing for all math operation methods inside the switch statements.
2. For DivideNumber method - not all code paths return a value
class Program
{
static void Main(string[] args)
{
double n1 = Convert.ToDouble(Console.ReadLine());
//string n2 = "";
double n2 = Convert.ToDouble(Console.ReadLine());
Console.Clear();
Console.WriteLine("Simple Calculator");
Console.WriteLine("\t 1) ADD");
Console.WriteLine("\t 2) SUBTRACT");
Console.WriteLine("\t 3) MULTIPLY");
Console.WriteLine("\t 4) DIVIDE");
Console.WriteLine("\t 5) QUIT");
Console.Write("Enter Selection: ");
int menuSelection =0;
// double total;
// menuSelection = Console.ReadLine();
switch (menuSelection)
{
case 1:
// total = Convert.ToInt32(AddNumbers("Results:"));
Console.WriteLine(AddNumbers(n1,n2));
break;
case 2:
Console.WriteLine(SubtractNumber(n1,n2));
break;
case 3:
Console.WriteLine(MultiplyNumber(n1,n2));
break;
case 4:
Console.WriteLine(DivideNumber(n1,n2));
break;
case 5:
break;
default:
Console.WriteLine("Invalid Selection !");
Console.ReadLine();
return;
}
//Ask user to enter two numbers
Console.WriteLine();
Console.Write("Enter Number 1:", n1);
// number1 = Console.ReadLine();
Console.Write("Enter Number 2:", n2);
// number2 = Console.ReadLine();
}
public static double AddNumbers(double number1, double number2)
{
return number1 + number2;
}
public static double SubtractNumber(double number1, double number2)
{
return number1 - number2;
}
public static double MultiplyNumber(double number1, double number2)
{
return number1 * number2;
}
public static double DivideNumber(double number1, double number2)
{
if (number1 == 0 && number2 == 0)
{
Console.WriteLine("Cannot Divide by Zero. Try Again");
return 0;
}
else
{
return number1 / number2;
}
}
1st mistake You are taking input after calling switch cases
2nd mistake your function have two parameters so pass them.
like DivideNumber(number1,number2) in your switch case
hope you understand
one thing i notice is you are taking input in string and your function takes double parameters so you need to convert string to double.
Give you idea use double to take input like double n1 = Convert.ToDouble(console.readline()); as input from console is string.
you are calling your function return AddNumbers();
but have declared it as public static double AddNumbers(double number1, double number2)
AddNumbers expected 2 numbers, you have passed 0.
You don't return anything from DivideNumbers, though you have declared it to return a double. public static double DivideNumber
The program makes no sense as it is. You are trying to do the operation before they've even given you the numbers. You should try to Rubber Duck this one yourself
This should do what your trying to accomplish.
This question already has answers here:
Get next smallest Double number
(3 answers)
Closed 8 years ago.
Is there a way to retrieve the successor or the predecessor a certain double? Note that I'm not looking for a "small constant", like double.Epsilon, but for "the smallest positive number that can be added or subtracted from a given value".
You could take binary representation and add one to the fraction part. Example:
using System;
public class Test
{
static void DoubleTest(double value)
{
var binary = BitConverter.DoubleToInt64Bits(value);
binary++;
var newValue = BitConverter.Int64BitsToDouble(binary);
var difference = newValue - value;
Console.WriteLine("value = {0:R}", value);
Console.WriteLine("value' = {0:R}", newValue);
Console.WriteLine("dx = {0:R}", difference);
Console.WriteLine();
}
public static void Main()
{
DoubleTest(0.0000000004);
DoubleTest(4.0000000000);
DoubleTest(4000000000.0);
}
}
prints:
value = 4E-10
value' = 4.0000000000000007E-10
dx = 5.169878828456423E-26
value = 4
value' = 4.0000000000000009
dx = 8.8817841970012523E-16
value = 4000000000
value' = 4000000000.0000005
dx = 4.76837158203125E-07