I want to get a number from the user, and then multiply that number with Pi. my attempt at this is below. But a contains gibberish. For example, if I insert 22, then a contains 50. What am I doing wrong? I don't get any compiler errors.
double a,b;
a = Console.Read();
b = a * Math.PI;
Console.WriteLine(b);
I'm not sure what your problem is (since you haven't told us), but I'm guessing at
a = Console.Read();
This will only read one character from your Console.
You can change your program to this. To make it more robust, accept more than 1 char input, and validate that the input is actually a number:
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
if (double.TryParse(Console.ReadLine(), out a)) {
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
} else {
//user gave an illegal input. Handle it here.
}
a = double.Parse(Console.ReadLine());
Beware that if the user enters something that cannot be parsed to a double, an exception will be thrown.
Edit:
To expand on my answer, the reason it's not working for you is that you are getting an input from the user in string format, and trying to put it directly into a double. You can't do that. You have to extract the double value from the string first.
If you'd like to perform some sort of error checking, simply do this:
if ( double.TryParse(Console.ReadLine(), out a) ) {
Console.Writeline("Sonuç "+ a * Math.PI;);
}
else {
Console.WriteLine("Invalid number entered. Please enter number in format: #.#");
}
Thanks to Öyvind and abatischev for helping me refine my answer.
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
The main reason of different input/output you're facing is that Console.Read() returns char code, not a number you typed! Learn how to use MSDN.
I think there are some compiler errors.
Writeline should be WriteLine (capital 'L')
missing semicolon at the end of a line
double a, b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
a = double.Parse(Console.ReadLine());
b = a * Math.PI; // Missing colon!
Console.WriteLine("Sonuç " + b);
string str = Console.ReadLine(); //Reads a character from console
double a = double.Parse(str); //Converts str into the type double
double b = a * Math.PI; // Multiplies by PI
Console.WriteLine("{0}", b); // Writes the number to console
Console.Read() reads a string from console A SINGLE CHARACTER AT A TIME (but waits for an enter before going on. You normally use it in a while cycle). So if you write 25 + Enter, it will return the unicode value of 2 that is 50. If you redo a second Console.Read() it will return immediately with 53 (the unicode value of 5). A third and a fourth Console.Read() will return the end of line/carriage characters. A fifth will wait for new input.
Console.ReadLine() reads a string (so then you need to change the string to a double)
Sometime in the future .NET4.6
//for Double
double inputValues = double.Parse(Console.ReadLine());
//for Int
int inputValues = int.Parse(Console.ReadLine());
double a,b;
Console.WriteLine("istenen sayıyı sonuna .00 koyarak yaz");
try
{
a = Convert.ToDouble(Console.ReadLine());
b = a * Math.PI;
Console.WriteLine("Sonuç " + b);
}
catch (Exception)
{
Console.WriteLine("dönüştürme hatası");
throw;
}
Console.Read() takes a character and returns the ascii value of that character.So if you want to take the symbol that was entered by the user instead of its ascii value (ex:if input is 5 then symbol = 5, ascii value is 53), you have to parse it using int.parse() but it raises a compilation error because the return value of Console.Read() is already int type. So you can get the work done by using Console.ReadLine() instead of Console.Read() as follows.
int userInput = int.parse(Console.ReadLine());
here, the output of the Console.ReadLine() would be a string containing a number such as "53".By passing it to the int.Parse() we can convert it to int type.
You're missing a semicolon: double b = a * Math.PI;
Related
I'm doing a school assignment in which we are assigned to make a program that asks the user to input a number. It then changes the input into a number and determines if the number is an integer or a decimal. If not possible, it says this to the user. The program cannot have errors that the users input can cause.
My problem is the part where the program determines if the feed is an integer or a decimal, if I input an integer, it says the number is integer and decimal, if I input a decimal, it ends in an error. The program never reaches catch (Exception) if the input is wrong.
public static void ITellYouYourNumbers(float number)
{
try
{
float d = number;
int isInt = (int)d;
Console.WriteLine("The number is a integer");
float isFloat = (float)d;
Console.WriteLine("The number is a decimal");
}
catch (Exception)
{
Console.WriteLine("Your input cannot be changed into a number. Try again.");
Console.ReadLine();
throw;
}
}
static void Main(string[] args)
{
Console.WriteLine("Write a number");
float num = float.Parse(Console.ReadLine());
ITellYouYourNumbers(num);
}
I've tried determening the d in different ways, such as:
decimal d = number
Console.WriteLine((d % 1) == 0);
d = number
Console.WriteLine((d % 1) == 0);
and
(d % 1) < epsilon
but nothing I've tried works. If the input is integer, it shows as an integer and decimal, if I input a decimal, it says that an error occured in the float num = float.Parse(Console.ReadLine()); , but it doesn't show up as an error in the program itself.
First, float.Parse() will fail with an exception if the string you put in can not be parsed as a float (beware of the high and low limits too, there are minimum and maximum values) and the exception will not be stopped by the catch since it was not generated in the try-catch block.
Second, a float can always be casted to an int.
Third, you are casting d to a float while d is already a float so why would it not work ?
Fourth, you are putting your float parameter (called "number") in another float inside the function (called "d"). While not wrong technically speaking, it bothers me to duplicate a value when you have no plan to modify either instance of it.
If you can modify the main, call directly your ITellYouYourNumbers function and put the string in without trying to parse it. If I understand the instructions of your exercise correctly, all you have to do is check that
1/ The string is not empty even after removing all blank characters at both ends.
2/ After trimming, it contains only numbers and at most one '.' or ',' character.
3/ If it contains a '.' or ',', it is a decimal. Otherwise, it is an integer.
If you are actually supposed to cast the input as a number, you can check if it represents an integer by exploiting the fact that int x = (int)y will get the integer part of y and put it in x.
After that, you just have to check whether x==y or not.
I need a console app that changes the sign to a certain typed number. You type 10, it gives you -10. And so on. I've managed to do that, but I can't do it if I type 1.5 for example. Or any decimal number.
I get "Input string was not in a correct format".
this is what I did.
string inputData = Console.ReadLine();
int a = Convert.ToInt32 (inputData);
int b = a * (-1);
Console.WriteLine(b);
Console.ReadLine();
You need to use decimal as a variable type if you want to work with decimal numbers
If so, use Convert.ToDecimal instead of ToInt32
You don't really need to use multiplication here, it's enough just to use -a instead
string inputData = Console.ReadLine();
decimal a = Convert.ToDecimal (inputData);
decimal b = -a;
Console.WriteLine(b);
Console.ReadLine();
I have found this answered in other places using loops, but I wasn't sure if there is actually a function that I'm not finding that makes this easier, or if this is a possible (in my opinion) negative side to C#.
I'm trying to read in a double from user input like this:
Console.WriteLine("Please input your total salary: ") // i input 100
double totalSalary = Console.Read(); //reads in the 1, changes to 49.
I've found a couple other posts on this, and they all have different answers, and the questions asked aren't exactly the same either. If i just want the user input read in, what is the best way to do that?
Try this:
double Salary = Convert.ToDouble(Console.ReadLine());
You'll have to check the entire thing on it's way in.. as Console.Read() returns an integer.
double totalSalary;
if (!double.TryParse(Console.ReadLine(), out totalSalary)) {
// .. error with input
}
// .. totalSalary is okay here.
Simplest answer to your question:
double insert_name = Double.Parse(Console.ReadLine());
string input = Console.ReadLine();
double d;
if (!Double.TryParse(input, out d))
Console.WriteLine("Wrong input");
double r = d * Math.Pi;
Console.WriteLine(r);
I have a homework that I just can't figure out how to do. I'm not sure if the teacher wrote it wrong(he is a bad typer) or if there is a way to accomplish the task.
I work in Visual C# 2010 Express - Console Application
My task is to:
Read a four digit integer, such as 5893, from the keyboard and display the digits separated from one another by a tab each. Use both integer division and modulus operator % to pick off each digit. If the user enters 4567, the output looks like:
4567
4 5 6 7
Sure I know how to separate the numbers by using \t as well as reading the input and displaying it to the user. But how am I supposed to 'pick off' each digit with division and the remainder operators? Maybe he means something else, but not sure.
And another question...
How do I make sure that what the user types in is a number and not a letter?
Do I have to use Char.IsLetter, because I couldn't figure out how to use it on a parsed string.
Example:
string number1;
int x;
Console.Write("Please enter a number to calculate: ");
number1 = Console.ReadLine();
x = Int32.Parse(number1);
What method am I supposed to use and where do i put it in? Because now i only get an error and the application shuts down if I try to enter e letter.
The first question is really more about maths than programming. You know what the division and modulus operators do. Think about how you could use them to get the last (least significant) digit. Once you've done that you can apply a similar technique for the 2nd digit (tens) and then the same for hundreds and thousands and so on.
You've already found Char.IsLetter, but there is also Char.IsDigit, which does what you want more directly. You can do this check for one character and what you have is a string of characters. Have a look at a foreach loop.
System.Int32.TryParse() might be a better choice when converting the String.
Yes, your assignment makes sense. Say you have an integer x = 4567. To pick out the digit at position A you would use:
result = (int)((x / (A * 10)) % 10);
The first part of this (x / (A * 10)) "shifts" x to the right. So a value of A = 1 would divide 4567 by 10 which results in 456.7. You then use the modulo operator "%" to pick out the unit part of that number. Finally you convert to an int to remove the fractional part.
Ok, I won't give the whole solution (after all, this is homework ;)).
This code would check if there's four characters in input:
string input;
do
{
input = Console.ReadLine();
if (input.Length != 4)
Console.WriteLine("You have to enter FOUR digits");
} while (input.Length != 4);
This could be one way of checking the digits:
bool isOk = true;
foreach (char c in input.ToArray())
{
if (!Char.IsDigit(c))
{
Console.WriteLine("You have to enter four DIGITS");
isOk = false;
break;
}
}
This approach doesn't deal with math but you could do that just as well:
int num = int.Parse(input);
int tensOfThousands = num / 10000;
int thousands = (num - tensOfThousands) / 1000;
int lastDigit = num % 10;
//the rest of the digits are up to you ;)
For everybody new to C#, the solution can be simpler.
// Variables
int number = 1234;
int remainder;
string s = "";
while (number > 0) {
remainder = number % 10;
s = remainder + "\n" + s;
number /= 10;
}
Console.Write (s);
I'm doing a homework project that requires this:
Below you will find the code that I have written to compute the square root of a number using the Newton-Raphson method. Include it in your project. For this project your job will be to write a test harness that tests the code that I have written. Carefully read the method prologue to understand how the function should work. Your test harness will provide a loop that:
Prompts the user to enter in a test value.
Gets the user's input. If a zero is entered, your program will print out a report and terminate.
Calls the Sqrt method provided in this project, and saves the return value in a double variable.
Calls the Sqrt method that is built into the Math class and saves the return value in a second double variable.
Compare these two values to see if they are equal.
When the user indicates that they are done (by entering a zero) display a report that shows this information:
* How many test cases you executed
* How many passed
* How many failed
So I've done all this without any problems in about 15 minutes, however for extra credit he asks us to find what is wrong with his Sqrt method and fix it so its return value equals the Math.Sqrt return value of the .net framework. I can't seem to find the problem in his method, and I want to find it, so I was wondering if anyone could point me in the right direction as to what the problem is with his Sqrt method? Thanks.
Here is my complete code:
// declare variables
double userInput = 0.0;
double debrySqrtReturnValue = 0.0;
double dotNetSqrtReturnValue = 0.0;
int testCasesExecuted = 0;
int testsPassed = 0;
int testsFailed = 0;
bool isEqual = false;
do
{
// Prompt the user to enter in a test value
Console.Write("Please enter a positive integer value: ");
userInput = double.Parse(Console.ReadLine());
if (userInput != 0)
{
debrySqrtReturnValue = Sqrt(userInput);
dotNetSqrtReturnValue = Math.Sqrt(userInput);
Console.WriteLine("The square root of {0} is: {1}", userInput, debrySqrtReturnValue);
Console.WriteLine("The real square root of {0} is: {1}\n", userInput, dotNetSqrtReturnValue);
if (debrySqrtReturnValue == dotNetSqrtReturnValue)
isEqual = true;
else
isEqual = false;
if (isEqual)
testsPassed++;
else
testsFailed++;
testCasesExecuted++;
}
} while (userInput != 0);
Console.WriteLine("\n\n--------------------------------Report---------------------------------");
Console.WriteLine("test cases excecuted: {0}", testCasesExecuted);
Console.WriteLine("tests passed: {0}", testsPassed);
Console.WriteLine("tests failed: {0}", testsFailed);
Console.ReadLine();
}
// The Sqrt method
// Purpose: to compute the square root of a number
// Parameters: a positive, non-zero integer
// returns: a double, which is the square root of the number
// ---------------------------------------------------------
static double Sqrt(double number)
{
// constants to use in the calculation
const int FIRST_APPROX = 2;
const double EPS = 0.001;
// a local variable
double xN = 0;
// pick 2 as first approximation
double xNPlus1 = FIRST_APPROX;
do
{
xN = xNPlus1;
xNPlus1 = xN - ((xN * xN - number) / (FIRST_APPROX * xN));
} while (Math.Abs(xNPlus1 - xN) > EPS);
return xN;
}
}
Try setting const double EPS = 0.000000001; - that's your epsilon. That's what determines the precision of your answer.
Math.sqrt returns NaN if the argument is negative. Also, I think EPS would be much smaller.