First of all I am a beginner in C#, I have just started to play around with it as that's what my University course requires.
My problem is an assignment question which says:
h) To test if a number entered has an integer value. Hint: The number will have to be of type Double. If, for example, the number is 2.5 that doesn’t have an integer value but 2 does. You will need to use Convert.ToInt32(TheNumber) to convert the Double to an Int then compare the two.
double a, b, result;
Console.WriteLine("Input a number");
a = Convert.ToDouble(Console.ReadLine());
b = Convert.ToInt32(a);
This is what I have at the moment and I don't know how to compare these 2 to test which one is an integer. I am pretty sure that you have to use an if statement but how to tell C# to test which of these 2 numbers is an integer and which one isn't!
Any help is highly appreciated :)
Update:
I'd do it like this:
double d;
int i;
Console.WriteLine("Input a number");
d = Convert.ToDouble(Console.ReadLine());
i = Convert.ToInt32(d);
if(i == d) Console.WriteLine("It is an integral value");
This means: if you convert a double to an integer, it will lose all its digits after the decimal point. If this integer has the same value as the double, then the double had no digits after the decimal point, so it has an integer value.
You can use TryParse method which returns boolean
double mydouble;
int myInt;
string value = Console.ReadLine();
if (double.TryParse(value, out mydouble))
{
//This is double value, you can perform your operations here
}
if (int.TryParse(value, out myInt))
{
//This is Int value, you can perform your operation here
}
Should be like this:
double d;
int i;
Console.WriteLine("Input a number");
d = Convert.ToDouble(Console.ReadLine());
i = Convert.ToInt32(d);
if(i == d) Console.WriteLine("It is an integral value");
I think you can use TryParse with do while loop
int number;
string value;
do
{
Console.Write("Enter a number : ");
value =Console.ReadLine();
if (!Int32.TryParse(value, out number))
{
Console.WriteLine("Wrong Input!!!!");
}
}while (!Int32.TryParse(value, out number));
Related
Having some problems with my Console Calculator
I want to prohibit user inputing a words instead of numbers.
I wrote this code and its converting words to zero but i want user to type a number instead of words. And if user still typing words program should ask user to type number.
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("----------------------");
Console.WriteLine("------Calculator------");
Console.WriteLine("----------------------");
do
{
double num1 = 0;
double num2 = 0;
double result = 0;
bool result0;
Console.WriteLine("Enter number one: ");
try
{
double.TryParse(Console.ReadLine(), out num1);
if ()
{
Console.WriteLine("Incorrect number!\nType another number:");
num1 = Convert.ToDouble(Console.ReadLine());
}
}
catch (Exception e)
{
}
Console.WriteLine("Enter number two: ");
num2 = Convert.ToDouble(Console.ReadLine());
You have to use double.TryParse() inside a if condition with negation operator.
If you want to force user to show "Incorrect number!\nType another number:" message till the user enters correct integer, use while() loop instead of if() condition.
while (!double.TryParse(Console.ReadLine(), out num1))
Console.WriteLine("Incorrect number!\nType another number:");
Why we should use double.TryParse() inside if condition?
double.TryParse(), parse string value to double and return true if conversion succeeded or not.
In your case, if user enters word instead of number then conversion will fail and use of !(negation) will iterate the loop again.
I want to determine the next decimal after a certain decimal programmatically.
For example, I have the decimal 0.0000041
I want to programmatically generate 0.0000042 in a function.
If I ran the function again after running it with 0.0000042 the new number would be 0.0000043
If I ran the function with the decimal being 0.0000049 the new number would be 0.0000050 etc....
Is there a way to do this?
I do not know where to start or what references to look at to do something like this.
Thank you.
You seem to be looking for something like this: (Check below if you want to specify the precision manually)
static decimal GetNextDecimal(decimal input)
{
int count = BitConverter.GetBytes(decimal.GetBits(input)[3])[2];
return input + (1m / (decimal)Math.Pow(10, count));
}
Usage:
decimal num1 = 0.0000041m;
decimal num2 = 0.00002m;
decimal next = GetNextDecimal(num1);
decimal next2 = GetNextDecimal(num2);
Console.WriteLine(next);
Console.WriteLine(next2);
Output:
0.0000042
0.00003
I used a little help of this answer to get the number of the decimal places.
If you originally wanted to specify the precision manually, you can use the following instead:
static decimal GetNextDecimal(decimal input, int precision)
{
return input + (1m / (decimal)Math.Pow(10, precision));
}
..which allows you to do something like this:
decimal num1 = 0.003m;
decimal next = GetNextDecimal(num1, 3);
decimal next2 = GetNextDecimal(num1, 4);
Console.WriteLine(next);
Console.WriteLine(next2);
Output:
0.004
0.0031
I'm trying to check if the user's response is a double or an int, but the int is specific, whereas the double is not, as I probably made a right mess of explaining it, here's the code:
Console.WriteLine("\n 2) Q: How old is Sally? \n");
int nSallyAge = Convert.ToInt32(Console.ReadLine());
double dSallyAge = Convert.ToDouble((nSallyAge));
if (nSallyAge == 62 || dSallyAge == 62.0)
{
// Increase Score
sUser1Score++;
Console.WriteLine("\n A: Correct, Sally's age is 62, you have been awarded 1 point. \n");
Console.ReadLine();
}
What I'm trying to do, is instead of dSallyAge HAS to equal 62.0, it just has to equal any double figure.
I would approach this problem by first creating a method that gets a double from the user (that will, of course, also accept an int). This removes error handling from your main code.
NOTE in the code below, Math.Truncate can be replaced by Math.Floor, with the same result:
private static double GetDoubleFromUser(string prompt)
{
double input;
while (true)
{
if (prompt != null) Console.Write(prompt);
if (double.TryParse(Console.ReadLine(), out input)) break;
Console.WriteLine("Sorry, that is not a valid number. Please try again.");
}
return input;
}
Then, in my main code, I would get the number from the user, and use the Math.Truncate method to just read the first part of the double passed in by the user (this is what it sounds like you want to do). This means that if the user enters anything from 62 to 62.0 to 62.999, it will truncate the result to '62':
double nSallyAge = GetDoubleFromUser("2) Q: How old is Sally? ");
if (Math.Truncate(nSallyAge) == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Other alternative ways to use this are:
int sallyAge = Math.Truncate(GetDoubleFromUser("2) Q: How old is Sally? "));
if (sallyAge == 62)
{
// Increase Score
sUser1Score++;
Console.WriteLine("A: Correct, Sally's age is 62, you have been awarded 1 point.");
Console.ReadLine();
}
Or, you could use an input function that returns an int in the first place:
private static int GetIntFromUser(string prompt)
{
return Math.Truncate(GetDoubleFromUser(prompt));
}
In your code above, you are converting the input to an integer and then converting the int result to a double.
Assuming that you are only allowing numerical values to be entered, why not try something like this. This will identify if the input contained decimals or not:
string input = Console.ReadLine();
int iSallyAge;
double dSallyAge;
if (!Int32.TryParse(input, iSallyAge))
{
dSallyAge = Double.Parse(input);
}
You should be using Double.TryParse to parse the user input to a double and then test that value to see whether it's equal to 62.0.
double age;
if (double.TryParse(Console.ReadLine(), out age) && age == 62.0)
{
// age is 62.
// ...
}
I am working through learning C# myself (not homework) and am confused about method overloading when there is user input.
I am doing an exercise that allows the user to input a bid amount for an item. I need to include 3 overloaded methods (int, double, string). (The exercise says to use double not decimal.)
I know how to write the overloaded methods, my confusion comes with the user input. If I accept the input (ReadLine) as a string, it chooses the string method, if I accept the input as a int, the int method is called. How do I deal with this? Do I use tryParse? How can I do this with 3 possible input methods (int, double, string)?
Also, to add a frustrating twist, for the string to be accepted it must be numeric and preceded with '$' sign or numeric followed by "dollars". I am hoping that I completed that correctly in the code below. Wasn't sure how to trim by string, so I had to do it by character...
Hoping for a basic/simple explanation, as I haven't learned anything too fancy yet.
Thank you!
namespace Auction
{
class Program
{
static void Main(string[] args)
{
string entryString;
//int entryInt; // do I need this?
//int entryDouble; // do I need this?
double bidNum;
const double MIN = 10.00;
Console.WriteLine("\t** WELCOME TO THE AUCTION! **\n");
Console.Write("Please enter a bid for the item: ");
entryString = Console.ReadLine().ToLower();
double.TryParse(entryString, out bidNum); // this turns it into a double...
BidMethod(bidNum, MIN);
Console.ReadLine();
}
private static void BidMethod(int bid, double MIN)
{ // OVERLOADED - ACCEPTS BID AS AN INT
Console.WriteLine("Bid is an int.");
Console.WriteLine("Your bid is: {0:C}", bid);
if (bid >= MIN)
Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN);
else
Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN);
}
private static void BidMethod(double bid, double MIN)
{ // OVERLOADED - ACCEPTS BID AS A DOUBLE
Console.WriteLine("Bid is a double.");
Console.WriteLine("Your bid is: {0:C}", bid);
if (bid >= MIN)
Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN);
else
Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN);
}
private static void BidMethod(string bid, double MIN)
{ // OVERLOADED - ACCEPTS BID AS A STRING
string amount;
int amountInt;
if (bid.StartsWith("$"))
amount = (bid as string).Trim('$'); // Remove the $
if (bid.EndsWith("dollar"))
amount = bid.TrimEnd(' ', 'd', 'o', 'l', 'l', 'a', 'r', 's');
else
amount = bid;
Int32.TryParse(amount, out amountInt); // Convert to Int
Console.WriteLine("Bid is a string.");
Console.WriteLine("Your bid is: {0:C}", bid);
if (amountInt >= MIN)
Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN);
else
Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN);
}
}
}
Assuming that you are looking to support various ways of entering a dollar amount, then I would suggest your idea of using TryParse could work:
First use int.TryParse - as int is most restrictive (doesn't
allow decimal point etc)
Second use double.TryParse
Finally, if neither of those work, keep as a string.
I think that replacing int and double versions with a decimal version would be more appropriate since decimal is more convenient for storing money values (search SO for more details).
So, read input, search for a dollar sign, if there is none, use decimal.TryParse() and a decimal overload else use the string overload.
As there is no difference in processing a number whether it contains a dollar sign or not, I would do the following.
...
string entryString = Console.ReadLine();
BidMethod(entryString, 10.00m); // m stands for decimal, d for double
...
private static void BidMethod(string bid, decimal min)
{
decimal number;
if (decimal.TryParse(bid.Replace("$", ""), out number))
{
Console.WriteLine("Your bid is: {0:C}", bid);
if (number >= min)
Console.WriteLine("Your bid is over the minimum {0} bid amount.", min);
else
Console.WriteLine("Your bid is not over the minimum {0} bid amount.", min);
}
}
Based on my understanding and your comments:
Hence you need (or the exercise requests) to accept int, double or string only.
I think you would need to first check if the input value containing $ or not, if so then you can call the string function.
Then you will check the value as int using Int32.TryParse if succeeded then call the int function
Last step is by checking the value as double by using Double.TryParse
Double's length is way more than int, that's why you should be checking int first
using System;
using static System.Console;
namespace Auction
{
class Program
{
static void Main(string[] args)
{
string entryString;
decimal bidNum;
const decimal MIN = 10.00m;
Console.Write("Please enter a bid for the item: ");
entryString = Console.ReadLine().ToLower();
decimal.TryParse(entryString, out bidNum); // this turns it into a double...
BidMethod(bidNum, MIN);
Console.ReadLine();
}
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;