I am trying to create a C# calculator for a class, but when I try to use it it always returns blatantly wrong answers, like 1+3 = 100, or rounding down the decimal 2.33 to 50. It also crashes after the first input every time, which makes me think that its reading when i press enter for some reason, but I've looked and can't find documentation on any issue like that. Thanks in advance.
'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace calculator
{
class Program
{
static void Main(string[] args)
{
//set label for finished functions to return to
start:
System.Console.WriteLine("choose from one of the following calculator choices");
System.Console.WriteLine("1: whole number");
System.Console.WriteLine("2: addition");
System.Console.WriteLine("3: sine");
System.Console.WriteLine("4: cosine");
System.Console.WriteLine("5: absolue value");
System.Console.WriteLine("6: quit");
int optionSelect = Convert.ToInt32(Console.ReadLine());
switch (optionSelect)
{
case 1:
System.Console.WriteLine("whole number");
System.Console.WriteLine("give a decimal");
decimal temp = System.Console.Read();
System.Console.WriteLine(Convert.ToInt32(temp));
goto start;
case 2:
System.Console.WriteLine("addition");
System.Console.WriteLine("first int");
int add1 = Convert.ToInt32(System.Console.ReadKey());
System.Console.WriteLine("second int");
Console.ReadLine();
int add2 = Convert.ToInt32(System.Console.Read());
Console.ReadLine();
int answer = add1+add2;
System.Console.WriteLine("the answer is " + answer);
goto start;
case 3:
System.Console.WriteLine("sine");
System.Console.WriteLine("enter your angle in radians");
double numSin = Console.Read();
System.Console.WriteLine(Math.Sin(numSin));
goto start;
case 4:
System.Console.WriteLine("cosine");
System.Console.WriteLine("enter your angle in radians");
double numCos = Console.Read();
System.Console.WriteLine(Math.Cos(numCos));
goto start;
case 5:
System.Console.WriteLine("absolute value");
System.Console.WriteLine("enter a number");
double num = Convert.ToDouble(Console.Read());
System.Console.WriteLine(Math.Abs(num));
goto start;
case 6:
System.Console.WriteLine("shutting down...");
goto start;
default:
System.Console.WriteLine("invalid input");
goto start;
}
}
}
}
`
So there are multiple problems in your code.
Console.Read will return the corresponding ASCII code for the first character that you enter. Here is a link with the ASCII table: http://www.asciitable.com/
So if you put in the console 0 is not actually 0 but the corespondent value for 0 in the ASCII table. 0=48, 1=49, 2=50 ... 9 = 50.
If you put multiple characters only the first one will be processed by Console.Read.
To fix your problem you could use as you did in the begging :
string line = Console.ReadLine();
and after that, you can convert that line to whatever you need like decimal x = Convert.ToDecimal(line). or int x = Convert.ToInt32(line)
Also please try to change that goto logic into a while.
Related
{
Console.ForegroundColor= ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkRed;
Console.Clear();
Console.WriteLine("Please enter your name and I will tell you how many letters your name has!");
string name = Console.ReadLine();
Count(name);
Console.WriteLine("Now tell me two numbers and I will multiply them!");
Console.Read();
try
{
Multiply();
}
catch (FormatException)
{
Console.WriteLine("You must enter a number!");
}
}
public static void Count(string name)
{
Console.WriteLine("Your name has {0} letters!", name.Length);
}
public static void Multiply()
{
string firstNum = Console.ReadLine();
string secondNum = Console.ReadLine();
int num = Int32.Parse(firstNum);
int num1 = Int32.Parse(secondNum);
int result = num * num1;
Console.WriteLine("The result is {0}", result);
}
Im a beginner and Im learning about methods so I made this simple code where the user should enter two numbers and I should multiply them, the problem is, whenever I enter two random numbers, I am getting some completely different numbers back no matter if i want to add them, multiply them or something third.
I cannot figure out why the "num1 * num2;" is not giving me a correct number. E.G. 54*19 should give me 1026, but instead its giving me -15.
you need to comment on the Console.Read(); line. this is the main cause.
I have run your code by commenting on the above line and it works as expected for me
Also, you need to handle the scenarios when the user can enter a non-integer input, so you could use int.TryParse for the same.
Also, try to handle the scenario where the integer value is very large and the multiplication of two numbers exceeds the integer max value.
I made a foreach loop that would take a user's input and subtract two numbers on the same line, I was hoping it would print out the difference between any two numbers, but it didn't. Instead, when I ran the code and entered the numbers, it printed a different answer which didn't make sense to me. I'm kind of a bit new to c# so I'm just experimenting with things, but if anyone knows what's wrong with my code please help me figure out what's wrong with it. Thanks!
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
your answer will initially be 0. So when you do answer -= you subtract the right-hand-site (e.g. 5) from zero, which will result in a negative outcome. I suppose you need to assign the first operat to your answer:
using System;
public class Program
{
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
var parts = sequence.Split('-');
answer = parts[0];
for(int i = 1; i < parts.Length; i++)
{
answer -= double.Parse(parts[i]);
}
Console.WriteLine(answer);
Console.ReadLine();
}
}
Of course you should check if there are at least two elements within parts.
Assuming you want 5 rather than -15?
You need to initialise the value of answer with the first number rather than subtract everything from a starting point of zero.
bool init;
string sequence;
double answer;
public void Main()
{
Console.WriteLine("<<SUBTRACTION CODE>>");
Console.WriteLine("");
Console.WriteLine("Enter a sequence of numbers and an operator to get subtracted answer ");
Console.WriteLine("Eg: 10-5");
sequence = Console.ReadLine();
foreach (var operation in sequence.Split('-'))
{
if (!init) {
answer = double.Parse(operation);
init = true;
}
else
answer -= double.Parse(operation);
}
Console.WriteLine(answer);
Console.ReadLine();
}
I have a menu with option.
Option 1: BMI caculator (option 1/case 1)
When entering the details in BMI calculator such as Height in Meters I am trying to get it to loop back and print an error message and ask again if the height that the user entered isn't a int (meters) for example if the user inputs a string say "M" it will not work and loops back to the initial question prompting for input IE: 2.1. I'm trying to use IF ELSE inside the switch/case. You can see in height section I can use goto case 1 to loop it but does not work for weight ( because that will go back to the beginning of case 1 and user would need to enter height again), Whatever the outcome of weight I need to keep the result of Height prior to weight so as to perform the final calculation BMI = . Sorry if this isn't clear, I'm really new and really stuck.
switch (optionsIn)
case 1:
{
Console.Clear();
Console.WriteLine("What is your height in meters");
double heightMax = 0.00;
string heightMeters = Console.ReadLine();
double.TryParse(heightMeters, out double heightM);
if (heightMax < heightM)
{
Console.Clear(); // nothing needs to run here , just clear to look better and move to collection of weight.
}
else
{
Console.Clear();
Console.WriteLine("Incorrect option try again");
Console.WriteLine("press enter to try again");
Console.ReadKey();
goto case 1; // better way to do it rather than goto case 1?
}
Console.WriteLine("Enter weight in Kgs"); // need to start here if incorrect input from user
double kgs = 00.00;
string weight = Console.ReadLine();
double.TryParse(weight, out double weightKgs);
if (kgs < weightKgs)
{
Console.Clear(); // nothing needs to run here , just clear console to look neat and move to calculating and printing BMI
}
else
{
Console.WriteLine("Incorrect option try again"); // cannot get to loop back to Enter weight
Console.WriteLine("press enter to return");
Console.ReadKey();
break;
}
double bmi = weightKgs / (heightM * heightM);
Console.WriteLine($"BmI is " + bmi);
Console.WriteLine("press any key to exit");
Console.ReadKey();
break;
}
I suggest method extraction:
public static double ReadDouble(string title, Func<double, bool> validation) {
// Keep Asking User until correct value is provided
while (true) {
// Show title if we have it
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (!double.TryParse(Console.ReadLine(), out double result))
// Not a double value at all; say, "bla-bla-bla"
Console.WriteLine("Syntax error. Please, try again.");
else if (validation != null && !validation(result))
// Not a valid double value, say, 123456.89 kg weight
Console.WriteLine("Not a valid value. Please, try again.");
else
return result;
}
}
then you can easily use it within switch \ case:
double heightM = ReadDouble("What is your height in meters", m => m > 0.3 && m < 3.0);
double weightKgs = ReadDouble("Enter weight in Kgs", m => m > 0.7 && m < 700.0);
double bmi = weightKgs / (heightM * heightM);
Console.WriteLine($"BmI is {bmi:F1}");
Instead of using goto - which is considered bad practice and is not all that much readable, try using a while or do/while loop instead.
Something like:
string input;
double heightMax = 0.0;
do {
input = Console.ReadLine();
double.TryParse(input, out double heightM);
Console.Clear();
} while (heightMax >= heightM);
Also, consider using functions for loading the data. Maybe you can think of some way of generalizing so that you can have only one function that you can reuse for all the stuff you need to load.
While loops runs through the if statement once and stops.
I am new to c#, so excuse me if I am overlooking something seemingly obvious. I am currently writing a program that visualizes the Collatz conjecture through console entries. The program begins by prompting the user to enter a natural number. The program is supposed to run that number through the formulae of the conjecture until it eventually reaches a value of 1. However, when I type in the number in console, the program runs it through one formula and crashes. It seems that is has a problem with the Double.Parse line. I already tried using the convert method and tried defining "num" as a decimal instead of a double.
{
Console.WriteLine("Enter a natural number:");
Double num = Convert.ToDouble(Console.ReadLine());
while (num != 1)
{
{
if (num % 2 == 0)
{
Console.WriteLine(num / 2);
num = Double.Parse(Console.ReadLine());
}
else
{
Console.WriteLine(num * 3 + 1);
num = Double.Parse(Console.ReadLine());
}
}
Console.ReadLine();
}
}
}
}
To be honest, I'm not positive what you're trying to achieve from the description (i.e., I have not idea what a Collatz conjecture visualization formula is), but I think I figured out what your issue is.
I think you're a little confused about Console.ReadLine(). This method pauses and waits for user input. As a result, during your first loop through the while statement, your program will pause and wait for user input. I think what you're trying to do is take the result of the formula in either the "if" or "else" section and capture that as the new value of "num."
Here is my best guess at what you're trying to achieve:
static void Main(string[] args)
{
Console.WriteLine("Enter a natural number:");
Double num = Convert.ToDouble(Console.ReadLine());
while (num != 1)
{
if (num % 2 == 0)
{
num /= 2;
Console.WriteLine(num);
}
else
{
num = num * 3 + 1;
Console.WriteLine(num);
}
}
Console.WriteLine(num);
Console.ReadLine();
}
Also, it looks like you might have an extra set of brackets within your while statement. It doesn't seem like that would compile as-is, so perhaps it is just the way in which you copied it into your question.
Sorry if this isn't the right. This is my first time posting here. I'm a first year Software student and for the life of me i cannot seem to get this to work. I know its something simple I'm missing but oh well. I tried doing this using methods but again no help. Maybe you guys could help me?
The problem is the code wont let me input after the "Are you a member (Y/N)" writline statement and just keeps giving me an output of 50.
static void Main(string[] args)
{
//Local Variable Declaration//
double rate1 = 10;
double rate2 = 3;
double maxCharge = 50;
double charge;
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3)
{
charge = hoursRented * rate1;
}
else
{
charge = (3 * rate1) + (hoursRented * rate2);
}
if (charge > maxCharge)
{
charge = maxCharge;
}
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y"))
{
charge = (charge * 1 / 10) - charge;
}
Console.WriteLine("Customer Charge : {0} Total Charge To Date : ", charge);
}
The problematic lines are below
Console.WriteLine("Enter number of hours (-999 to quit) : ");
int hoursRented = Console.Read();
if (hoursRented >= 3) {
and
Console.WriteLine("Are you a member? (Y/N) : ");
int memberStatus = Console.Read();
if (memberStatus.Equals("Y")) {
When you call Console.Read(), it reads only characters and returns it as an int. You seem to mistakenly think it will parse the character to an int.
Secondly, think what happens when you provide multiple characters as input to a single Console.Read() call. Interestingly, the remaining characters are read in the subsequent calls. So when you type any number followed by Enter in the first Console.Read it only, reads the first character, the subsequent characters, including the EOLN char are returned in the subsequent calls, instead of prompting you to enter information for the next call.
The fix is easy. Use Console.Readline() and int.parse (or its int.TryParse() variant
Then the corresponding code will look like below
Console.Write("Enter number of hours (-999 to quit) : ");
string hoursRentedStr = Console.ReadLine();
int hoursRented = int.Parse(hoursRentedStr);
if (hoursRented >= 3) {
and
Console.Write("Are you a member? (Y/N) : ");
string memberStatus = Console.ReadLine();
if (memberStatus.Equals("Y")) {
This is because you are just writing:
Console.WriteLine("Are you a member? (Y/N) : ");
and continuing through.
you must do it like this:
Console.WriteLine("Are you a member? (Y/N) : ");
Console.ReadLine();
and then:
int memberStatus = Int.Parse(Console.ReadKey());
your problem is that your are using Console.Read wich returns the ascii code of the next charachter as said by #juharr in the comments. so the solution is too simply replace Read By ReadLine and change your code like this, so that ReadLine wich is a string will be converted to the int value that you want
int hoursRented = int.Parse(Console.ReadLine());
And change your member status to a string to compare it with "Y" easily
string memberStatus = Console.ReadLine();
Note: if you want to validate the input you should use a int.TryParse instead of just a normal parse like I used as it returns a bool so you knows when it fails