I want to print the value of the amount of sales entered by user times .10. My first issue is I want to store a value that a user enters into sales then times that by .10 then print the value of sales. We I run the program I get two lines one is the amount of sales entered the other is .5.
const double COMMRATE = 0.10;
string inputstring;
double sales =5;
char response;
Console.Write("Do you want to Calculate Sales A or B or E...");
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
while (response == 'A')
{
Console.WriteLine("Enter Sales", sales.ToString("C"));
sales = sales * COMMRATE;
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
}
Your .5 is coming about because you've set the default value of sales to be 5, and 5 * 0.1 = 0.5.
But why is that happening? Let's take apart your loop:
It asks the user to enter an amount of sales. The second parameter is ignored, because "Enter Sales" has no format string placeholders. It does not perform line-reading of any form.
Without asking for input, it multiplies Sales by the commission rate and stores that to Sales.
Now it asks for user input,
which it immediately spits back out exactly as written (the amount-of-sales-entered line.)
What you actually need to be doing is a second Console.ReadLine() to get a string for the amount of sales, then use Double.ParseDouble() to get the entered amount of sales. Multiply that by your COMMRATE and print that back out- then give your "Do you want to Calculate..." question again, and then use the response from that to decide whether or not to continue the loop- currently, response is never getting modified, so you've created an infinite loop.
Unfortunately, you aren't even really close to the right code here. Your loop should look more like
while (response == 'A'){
Console.WriteLine("Enter Sales");
string salesStr = Console.ReadLine();
Console.WriteLine(Double.Parse(salesStr) * COMMRATE);
Console.WriteLine("Enter A to continue, anything else to quit");
response = Convert.ToChar(Console.ReadLine());
}
...which should get you started towards making your program do what you want.
Is this what you intend?
const double COMMRATE = 0.10;
string inputstring;
double sales;
char response;
Console.Write("Do you want to Calculate Sales A or B or E...");
inputstring = Console.ReadLine();
response = Convert.ToChar(inputstring);
while (response == 'A')
{
Console.WriteLine("Enter Sales");
inputstring = Console.ReadLine();
sales = Double.Parse(inputstring);
Console.WriteLine("Sales = " & sales);
Console.WriteLine("Commission = " & sales * COMMRATE);
}
I'm having a hard time discerning what exactly you're asking.
If you want to print the value multiplied by the COMMRATE then you should probably put the calculation above the write statement.
sales = sales * COMMRATE;
Console.WriteLine("Enter Sales", sales.ToString("C"));
Although since you said you want to STORE the value entered by the user and THEN print it times the COMMRATE maybe you should use something like
double calculatedSales = sales * COMMRATE
Console.WriteLine("Enter Sales", calculatedSales.ToString("C"));
so that you're not redefining the original sales amount
Related
l am writing a class assignment for a simple login program where user will input username, password and mobile number on the console. My problem is on the mobile number, l want them to input a 10 digit number and only 10, if they input less or more than 10 it must show an error. Here is my code so far:
Console.WriteLine("Please enter your Mobile Number:");
Console.WriteLine("**Please note Mobile Number should be 10 digits only e.g 07...");
//AVOIDS EXCEPTION HANDLING OF ENTERING ANY TYPE THAT IS NOT AN INTEGER
while (!int.TryParse(Console.ReadLine(), out Option)) {
Console.WriteLine("***************************************************");
Console.WriteLine("Please Enter a valid numerical value!");
Console.WriteLine("Please Enter option 1 or option 2:");
}
Read the console in string variable, count the length and check if the string is a digit.
//code
string mobNo = Console.ReadLine();
if(mobNo.Length == 10)
{
bool isNum = int.TryParse(mobNo);
if(isNum)
//continue code
}
//return error
Here is a simple calculator, to calculate how much candy you can get when dividing the kilogram price with the money you have allocated for candy.
In example: "Candy costs 5$ a kilo. I have 3.50$ allocated for candy. I would use this program to calculate the amount of candy I get."
It works fine until using decimals. I want to convert the string to Double so I can use decimals with the calculator. 4$ kilo price and 8$ money of course results to 2 kilos of candy. But if the kilo price was 4.80$ and I had 9.30$ money, I would only get an error and cause the command prompt to crash.
static void Main(string[] args)
{
//The variables
int int1;
int int2;
string text1;
string text2;
//The actual calculation
System.Console.Write("Please input the kilogram price of candy: ");
text1 = System.Console.ReadLine();
int1 = int.Parse(text1);
System.Console.Write("Please input the money allocated for candy ");
text2 = System.Console.ReadLine();
int2 = int.Parse(text2);
System.Console.WriteLine("With the amount of money you input you would get " + (int2 / int1) + " kilos of candy.");
}
}
}
You're using int variable types, which can only contain integer numbers, i.e. "whole" numbers without decimals, such as 1 and 42. As soon as you want to use decimals, you'll need a variable type that can support this.
C# has a few of those built in: float, double and decimal. Given you're working with monetary data, where precision and accuracy are very important, you must use decimal.
You also want to use the bool-returning TryParse() as opposed to the exception-throwing Parse() method.
So change your code to use decimal and decimal.TryParse():
decimal pricePerKilogram;
string input = Console.ReadLine();
if (!decimal.TryParse(input, out pricePerKilogram))
{
// show error or retry
}
You need to parse your inputs from decimal, not int. Here, try it this way:
System.Console.Write("Please input the kilogram price of candy: ");
decimal pricePerKilo = decimal.Parse(System.Console.ReadLine());
System.Console.Write("Please input the money allocated for candy ");
decimal amountAllocatedForCandy = decimal.Parse(System.Console.ReadLine());
System.Console.WriteLine("With the amount of money you input you would get " + (amountAllocatedForCandy / pricePerKilo) + " kilos of candy.");
System.Console.Read();
An int is a type that can only store whole numbers -- i.e. no fractional component/decimal digits -- which is why you got an error when you tried to parse a string number with decimal digits into an int. A decimal, on the other hand, is used to store numbers with fractional components.
Each type has its uses: you would never want to store, say, number of candy pieces using a decimal since that can only be a whole number. Doing so could lead to unnecessary confusion for future maintainers of your code and could lead to bugs that are hard to find.
that is because 4.80 or 9.30 is not integer.
double double1;
double double2;
string text1;
string text2;
//The actual calculation
System.Console.Write("Please input the kilogram price of candy: ");
text1 = System.Console.ReadLine();
double1 = double.Parse(text1);
System.Console.Write("Please input the money allocated for candy ");
text2 = System.Console.ReadLine();
double2 = double.Parse(text2);
System.Console.WriteLine("With the amount of money you input you would get " + (double2 / double1) + " kilos of candy.");
NOTE: INT stores integer value like 1 2 3 4 etc...
As to your question:
Just use doubles decimals in the first place!
decimal price;
decimal allowance;
Also, some additional unsolicited advice:
You've got a few issues here.
First of all, you'll need to swap your division in the WriteLine statement to get the correct calculation.
Also, I'd recommend renaming your variables to something more descriptive.
Here's your code with some modifications. I've commented each change.
//The variables
decimal price; //CHANGE: descriptive variables!
decimal allowance;
string priceInput;
string allowanceInput;
//The actual calculation
System.Console.Write("Please input the kilogram price of candy: ");
priceInput = System.Console.ReadLine();
price = decimal.Parse(priceInput); //CHANGE: use double.Parse here instead of int.Parse
System.Console.Write("Please input the money allocated for candy ");
allowanceInput = System.Console.ReadLine();
allowance = decimal.Parse(allowanceInput); //CHANGE: use double.Parse here instead of int.Parse
System.Console.WriteLine("With the amount of money you input you would get "
+ Math.Round(allowance / price, 2) + " kilos of candy.");
//CHANGE: Divide the money you have by the amount it costs to get the KG of candy.
EDIT: Added decimals due to working with money.
Absolute newbie to C#. Was trying to run this program and the output simply would not show any computations.Why? I did not want to go through p,q,r,s for add, sub, multiply, divide etc., Also, how can i put space between "Please enter a number" and userName?
string userName;
double x, y;
Console.WriteLine(" Enter Your Name ");
userName = Console.ReadLine();
Console.WriteLine(" Please Enter A Number "+ userName);
First = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter Another Number"+ userName);
Second = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("The addition of Two Numbers is",x,y, x*y);
Console.WriteLine("The substraction of Two Numbers is",x,y,x/y);
Console.WriteLine("The multiplication of Two Numbers is",x,y,x * y);
Console.WriteLine("The division of Two Numbers given is", x,y,x / y);
Console.ReadKey();
When you pass additional parameters to show output, you must tell WriteLine where to put it by adding placeholders to the format line, like this:
Console.WriteLine("The product of Two Numbers {0} and {1} is {2}", x, y, x*y);
Positions are zero-based. The printed value of the first additional parameter (i.e. x) will replace {0}; the value of y will replace {1}, and the value of x*y will replace {2} in the final output.
The reason you did not have to do it with userName is that you passed a single parameter:
Console.WriteLine("Please Enter Another Number " + userName);
The result of appending userName to "Please Enter Another Number" string is passed as a single parameter to WriteLine. You could rewrite it with a format specifier, like this:
Console.WriteLine("Please Enter Another Number {0}", userName);
Totally agree with dasblinkenlight. Additionally, you may meet this line of code
Console.WriteLine("{0}, {1}", "Hello", 53);
Result in this line being written: Hello, 53. {0} is the placeholder for the first argument after the format string, {1} is the second, and so on. This is called composite formatting in .NET - http://msdn.microsoft.com/en-us/library/txafckwd%28v=vs.110%29.aspx
I need to format the string as % but the user will enter the number already as %
i.e user enter 10, I need to show 10%
I tried {0:P} and {0:0%} but it always multiply the user number by 100
How can I simply add "%" to the input number without multiply it by 100 in the format {0:}?
You have two real options, add the % by hand
String.Format("Example: {0}%", userValue);
or devide the user number by 100 before you display it.
String.Format("Example: {0:P}", userValue / 100.0); //don't just do "100" or you will get errors from integer division if userValue is a int.
Can't you just append %:
userEnteredNumber.ToString() + "%";
What about
var showString = userInput + "%";
Then display showString wherever you need to show.
We use this format for formatting int value to percent without multipying by 100.
intPercent.ToString(#"0\%");
Newbie to the C# language and
I just finished creating a loan mortgage calculator and I am having trouble formatting my code below. What I am trying to do is format the monthly payment value to 2 decimal places and add the '$' symbol. Any help would be appreciated. Thanks!
Example input for my principle amount:
//User input for Principle amount in dollars
Console.Write("Enter the loan amount, in dollars(0000.00): ");
principleInput = Console.ReadLine();
principle = double.Parse(principleInput);
//Prompt the user to reenter any illegal input
if (principle < 0)
{
Console.WriteLine("The value for the mortgage cannot be a negative value");
principle = 0;
}
//Calculate the monthly payment
double loanM = (interest / 1200.0);
double numberMonths = years * 12;
double negNumberMonths = 0 - numberMonths;
double monthlyPayment = principle * loanM / (1 - System.Math.Pow((1 + loanM), negNumberMonths));
//Output the result of the monthly payment
Console.WriteLine("The amount of the monthly payment is: " + monthlyPayment);
Console.WriteLine();
Console.WriteLine("Press the Enter key to end. . .");
Console.Read();
What I am trying to do is format the monthly payment value to 2 decimal places and add the '$' symbol.
It sounds like you want to use the currency format specifier.
Console.WriteLine("The amount of the monthly payment is: {0:c}", monthlyPayment);
That won't always use the dollar symbol of course - it will use the currency symbol for the thread's current culture. You can always specify CultureInfo.InvariantCulture explicitly.
However, I'd strongly advise you not to use double for currency values. Use decimal instead.
From MSDN: Standard Numeric Format Strings
(look for 'The Currency ("C") Format Specifier')
Console.WriteLine("The amount of the monthly payment is: {0:C2} ", monthlyPayment);
You can use the Math.Round() function:
double inputNumber = 90.0001;
string outputNumber = "$" + Math.Round(inputNumber, 2).ToString();
To use 2 decimal places you can use:
Console.WriteLine("The amount of the monthly payment is: "$ " + Math.Round(monthlyPayment,2));