Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 months ago.
Improve this question
using System;
using System.Data;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
bool calc1 = false;
bool end = false;
double answer = 0.0;
double num1 = Convert.ToDouble(Console.ReadLine());
string op1 = Console.ReadLine();
double num2 = Convert.ToDouble(Console.ReadLine());
if (op1 == "*") ;
{
answer = (num1 * num2);
calc1 = true;
}
if (op1 == "/") ;
{
answer = (num1 / num2);
calc1 = true;
}
if (op1 == "+") ;
{
answer = (num1 + num2);
calc1 = true;
}
if (op1 == "-") ;
{
answer = (num1 - num2);
calc1 = true;
}
while (end == false) ;
{
string op2 = Console.ReadLine();
if (op2 == "*") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer * num3);
}
if (op2 == "/") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer / num3);
}
if (op2 == "+") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer + num3);
}
if (op2 == "-") ;
{
double num3 = Convert.ToDouble(Console.ReadLine());
answer = (answer - num3);
}
if (op2 == "=") ;
{
Console.WriteLine(answer);
end = true;
}
}
}
}
}
I am trying to create a multi integer calculator but for some reason, my while loop does not execute so once I enter the first 2 digits and operator, it stops running. Before hand, I had 2 while loops and it would run the second one but it would not print the answer variable when the user entered =.
your issue is the semicolon ; after the while condition.
Remove it. (and also all the ; after the if conditions!)
Currently the code is like that:
while (condition);
{ you big block of code } // <--- this is not part of the while loop
Because of the semicolon, it's actually the same as
while (condition)
;
the big block of code // <--- this is not part of the while loop
or even:
while (condition)
{
}
the big block of code // <--- this is not part of the while loop
If you remove the semicolon, then the block is now part of the loop;
while (condition)
{
the big block of code // <--- Now it's like you intended to write!
}
This is the same problem with the ifs, by the way.
If you write a if (condition);, that's like if (condition) { }, and the other block below will be always executed.
You put a semicolon after the while loop, nothing is inside of it.
If you want to have a forever loop, I suggest you use while(true)
Edit:
OP, If you wanted to exit the loop at any time, you could simply just do break; instead of setting the condition equal to false.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This is my code
Basic Calculator Using 2 methods
1 is the main method
2 is the operator
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
int num1;
int num2; //Variables for equation
string op;
//int Answer;
Console.Write("Enter the first number : ");
num1 = Convert.ToInt32(Console.ReadLine());
//User input for equation
Console.Write("Now enter your second number : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Ok now enter your operation ( x , / , +, -) ");
op = Console.ReadLine();
Methods1(); // This is the error, The error says
// There's no argumen given that corresponds
}
static int Methods1(int num1, int num2, string op)
{
if (op == "+")
{
return num1 + num2;
}
else if (op == "-")
{
return num1 - num2;
}
else if (op == "/")
{
return num1 / num2;
}
else if (op == "*")
{
return num1 * num2;
}
else
{
Console.WriteLine("Invalid Operator");
return 0;
}
}
}
}
You have called the Methods1() method without arguments. Change the code to the following:
using System;
namespace Test_app_1
{
class Program
{
static void Main(string[] args)
{
int num1;
int num2; //Variables for equation
string op;
int Answer;
Console.Write("Enter the first number : ");
num1 = Convert.ToInt32(Console.ReadLine());
//User input for equation
Console.Write("Now enter your second number : ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Ok now enter your operation ( * , / , +, -) ");
op = Console.ReadLine();
Answer = Methods1(num1, num2, op); // Now no error...
Console.WriteLine(Answer + "\nPress any key to exit..."); //You forgot to add Console.Writeline
Console.Read(); //Also forgot Console.Read
}
static int Methods1(int num1, int num2, string op)
{
if (op == "+")
{
return num1 + num2;
}
else if (op == "-")
{
return num1 - num2;
}
else if (op == "/")
{
return num1 / num2;
}
else if (op == "*")
{
return num1 * num2;
}
else
{
Console.WriteLine("Invalid Operator");
return 0;
}
}
}
}
I'm relatively new to programming and I'm working on various projects to get better at it. One is a calculator that I want to be able to solve more than just basic addition and subtraction. Currently, all I have is the basics with the quadratic formula. But my design weighs on user input to decide what to do. It prompts the user with "What would you like to do? Add: Sub: Div: Mul: Quad Equation:" After typic in "Add" the code operates normally but if I type in anything else like "Sub" or "Div". it does nothing. doesn't even spit back an error. As far as I can tell, my code is fine (well it's terrible code but it should work nonetheless) But I just do not know how to proceed.
using System;
namespace Better_Calculator
{
class Program
{
static void Main(string[] args)
{
double num01;
double num02;
double a;
double b;
double c;
System.Console.WriteLine("Welcome to how you are going to cheat through math lol");
System.Console.WriteLine("What would you like to do? \nAdd: \nSub: \nDiv: \nMul: \nQuad Equation: ");
if (Console.ReadLine() == "Add")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Add(num01, num02);
}
else if (System.Console.ReadLine() == "Sub")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Sub(num01, num02);
}
else if (System.Console.ReadLine() == "Mul")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Mul(num01, num02);
}
else if (System.Console.ReadLine() == "Div")
{
System.Console.WriteLine("what is the first number?");
num01 = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is the second number?");
num02 = Convert.ToInt32(Console.ReadLine());
Div(num01, num02);
}
else if (System.Console.ReadLine() == "Quad Equation")
{
System.Console.WriteLine("what is a?");
a = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is b");
b = Convert.ToInt32(Console.ReadLine());
System.Console.WriteLine("what is c");
c = Convert.ToInt32(Console.ReadLine());
Quad(a, b, c);
}
static void Add(double num01, double num02)
{
string answer = Convert.ToString(num01 + num02);
System.Console.WriteLine(answer);
}
static void Sub(double num01, double num02)
{
string answer = Convert.ToString(num01 - num02);
System.Console.WriteLine(answer);
}
static void Mul(double num01, double num02)
{
string answer = Convert.ToString(num01 * num02);
System.Console.WriteLine(answer);
}
static void Div(double num01, double num02)
{
string answer = Convert.ToString(num01 / num02);
System.Console.WriteLine(answer);
}
static void Quad(double a, double b, double c)
{
double bNeg = b * -1;
double bSqr = b * b;
double SqR = Math.Sqrt(bSqr - (4 * a * c));
double solvedAdd = (bNeg + SqR) / (2 * a);
double solvedSub = (bNeg - SqR) / (2 * a);
string answer = Convert.ToString(solvedAdd) + " or " + Convert.ToString(solvedSub);
System.Console.WriteLine(answer);
}
}
}
}
With every ´if´, you call Console.ReadLine() again, so if you enter "Quad Equation", your code has passed 5 Readlines until you reach the code that does Quad Equation.
Solution: Do only one Console.ReadLine() and put its result into a variable:
var userInput = Console.ReadLine();
and then, test against userInput in your if statements (ex.)e:
else if (userInput == "Sub")
You only need to do a ReadLine once and store the value, then use that to compare. For example:
var operation = Console.ReadLine();
if(operation == "Add")
{
// Do add stuff
}
But you should consider using a switch statement instead:
switch(operation)
{
case "Add":
// do Add Stuff
break;
case "Sub":
// do Add Stuff
break;
case "Mul":
// do Add Stuff
break;
// etc...
}
When we get input from console application from user may be they given as
CAPS, Small or combination of both
. In that situation you can use the following approach,
string value=Console.ReadLine();
if(string.Equals(value, "Add", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}
else if(string.Equals(value, "Sub", StringComparison.CurrentCultureIgnoreCase))
{
// Do add stuff
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
It is my code:
using System;
namespace ConsolePrimeNumberCalculator1
{
class Program
{
static void Main(string[] args)
{
Console.Title = "ConsolePrimeNumberCalculator1";
string input = Console.ReadLine();
int a, b, c, d, e = 0;
if (int.TryParse(input, out a))
{
if (a > 1)
{
for (b = 2; b <= a; b++)
{
d = 2;
c = 1;
while (d < b)
{
if (b % d == 0)
{
c = 0;
break;
}
d++;
}
if (c == 1)
{
e = 1 + e;
}
if (a > 50000)
{
Console.WriteLine("Number is Big");
break;
}
}
if (a < 50001)
{
Console.WriteLine(e);
}
}
else
{
Console.WriteLine("Number is Small");
}
}
else
{
Console.WriteLine("Number is not Integer");
}
if (a < 1)
{
if (!int.TryParse(input, out a))
{
Console.WriteLine("Number is Small");
}
}
Console.ReadKey();
}
}
}
My problem:
I wrote 2.3. But my application wrote this:
"Number is not integer" and "Number is Small"
"Number is not integer" is a true sentence. But I think "Number is Small" is a false sentence. Because 2.3 is not smaller than 1. Why does my application wrote "Number is Small"? Is it C# bug?
This is because your TryParse calls cannot parse it to an integer (this is why they are returning false).
This line:
int.TryParse(input, out a)
Will return false and a will be 0.
So when you hit your final if:
if (a < 1)
{
if (!int.TryParse(input, out a))
{
Console.WriteLine("Number is Small");
}
}
a is zero to start, it still can't parse it, so a remains zero and you hit this write.
int.TryParse("2.3", out a); will try to parse "2.3" as an integer, and if it succeeds, it will assign it's value to a (currently 0).
As TryParse fails (cannot convert "2.3" to int), it never assigns the value to a, which remains 0, hence the code falls in the else block.
int a = 0 stills 0 after parsing because the parse function fails... Try to debug and see it yourself
Actually you have int a = 0 than
(!int.TryParse(input, out a)) fails and
a is less than 1 that's why it is printing "Number is Small"
I am new here so please excuse me for the poor formatting,
I wrote a simple calculator in c# but it seems my multiplication and division are not working correctly.
when running the code it works fine until I try to output the answer and then it outputs "Error, Unknown operator" which is what I told it to output when it doesn't identify the operator stored in the operation variable.
here is the code (sorry for dumping so much code, I am not sure what is relevant and what is not):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class MainClass
{
public static void Main(string[] args) // method called "main", when the program starts, this runs
{
start:
// variable declarations
double Num1;
double Num2;
int operationId;
string operationName = "1";
string operationName2 = "1";
Char operation;
double answer;
// choosing an operator
Console.WriteLine("select an operation from the list and type it's associated number:");
Console.WriteLine("1 - sum \n" + "2 - subtraction \n" + "3 - division\n" + "4 - multipication \n");
operationId = Convert.ToInt32(Console.ReadLine());
// checking which operation has been chosen
if (operationId == 1)
{
operationName = "added to";
operationName2 = "added";
operation = '+';
} else if (operationId == 2)
{
operationName = "subtracted from";
operationName2 = "subtracted";
operation = '-';
} else if (operationId == 3)
{
operationName = "divided";
operationName2 = "divided by";
operation = '/';
} else if (operationId == 4)
{
operationName = "multiplied";
operationName2 = "multiplied by";
operation = '*';
} else
{
Console.WriteLine("Invalid option");
goto start;
}
// receving user input
Console.WriteLine("Insert a number to be " + operationName + ":");
Num1 = Convert.ToDouble (Console.ReadLine());
Console.WriteLine("Insert a number to be " + operationName2);
Num2 = Convert.ToDouble(Console.ReadLine());
//calculating answer
if (operation == '+')
{
answer = Num1 + Num2;
}
else if (operation == '-')
{
answer = Num1 - Num2;
}
else if (operationId == '/')
{
answer = Num1 / Num2;
}
else if (operationId == '*')
{
answer = Num1 + Num2;
} else
{
answer = 0000;
Console.WriteLine("Error, Unknown operator \n");
goto start;
}
Console.WriteLine();
Console.WriteLine("The result is:");
Console.WriteLine(answer);
Console.ReadKey();
Console.WriteLine();
goto start;
}
}
}
Your first 2 ifs check operation, the second 2 check operationId. Change the multiply and divide ones to also check operation.
//...
else if (operation == '/')
{
answer = Num1 / Num2;
}
else if (operation == '*')
{
answer = Num1 * Num2; //<-- Change to this from Num1 + Num2
}
//...
And by the way, your multiply block is adding the numbers, not multiplying. I've fixed that in my block above.
I guess the problem is with - 2 conditions are checking operation and 2 conditions are checking operationId. Perhaps you may want to change all the checks to be either with operation or with operationId.
if (operation == '+')
{
answer = Num1 + Num2;
}
else if (operation == '-')
{
answer = Num1 - Num2;
}
else if (operationId == '/')
{
answer = Num1 / Num2;
}
else if (operationId == '*')
{
answer = Num1 + Num2;
} else
{
answer = 0000;
Console.WriteLine("Error, Unknown operator \n");
goto start;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am trying to get this random number guessing game working. The program runs, but it doesn't give the "you won" message when you enter the correct number, and the hint feature does not give the feed back it is supposed to. Any help appreciated.
using System;
namespace randomNumberGame
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
var val = r.Next(1, 100);
var guess = 0;
bool correct = false;
var attemptsLeft = 5;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
while (!correct && attemptsLeft >= 1)
{
Console.Write("You have " + attemptsLeft + " lives left. Please enter your Guess: ");
string input = Console.ReadLine();
var message = "";
var difference = val - guess;
if (!int.TryParse(input, out guess))
{
Console.WriteLine("That's not a number.");
continue;
}
if (difference == 0)
{
Console.WriteLine("You have won");
correct = true;
}
else
{
if (Math.Abs(difference) >= 50)
{
message = Math.Sign(difference) == -1 ? "Very High" : "Very Low";
}
else if (Math.Abs(difference) < 50 && Math.Abs(difference) >= 20)
{
message = Math.Sign(difference) == -1 ? "High" : "Low";
}
else if (Math.Abs(difference) < 20 && Math.Abs(difference) >= 10)
{
message = Math.Sign(difference) == -1 ? "Moderatley High" : "Moderately Low";
}
else if (Math.Abs(difference) < 10)
{
message = Math.Sign(difference) == -1 ? "Somewhat High" : "Somewhat Low";
}
else Console.WriteLine("???");
}
attemptsLeft--;
}
}
}
}
"it doesn't give the you won message when you enter the correct number"
Actually, it does! But then the program exits so quickly that you never see it. To solve this, add a line that waits for the user to press a key at the end of your Main method, so you can see the final result:
// Add this as the last line of the main method:
Console.ReadKey();
"the hint feature does not give the feed back it is supposed too"
This is because you never output the hint message! At the end of your while loop, add a line to do so:
// Add this as the last line of the while loop:
Console.WriteLine(message);
These things can be found easily if you simply set a breakpoint in your code (in Vistal Studio, click the left margin next to one of the lines and a red dot will appear (or press F9)). Then you can step through the code using F10 and you can watch the values of local variables change and see what is happening step-by-step.
Another way to help avoid problems (and to narrow down where they occur) is to take out chunks of code that does something specific and put it in a method. This will make it easier to debug in the long run.
For example, we can write methods that take in a string to display to the user as a prompt for input, and return a strongly-typed value based on their entry. We can also have these methods take in an optional validation method that can be used to validate that the input they entered falls within a valid range (like a number from 1 to 100, or a name that's not longer than 25 characters):
public static string GetStringFromUser(string prompt,
Func<string, bool> validator = null)
{
string result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
result = Console.ReadLine();
} while (!(validator?.Invoke(result) ?? true));
return result;
}
public static int GetIntFromUser(string prompt,
Func<int, bool> validator = null)
{
int result;
var cursorTop = Console.CursorTop;
do
{
ClearSpecificLineAndWrite(cursorTop, prompt);
} while (!int.TryParse(Console.ReadLine(), out result) ||
!(validator?.Invoke(result) ?? true));
return result;
}
private static void ClearSpecificLineAndWrite(int cursorTop,
string message)
{
Console.SetCursorPosition(0, cursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, cursorTop);
Console.Write(message);
}
We can also write a helper method to get our "difference string", which could take in the guess, the number, and the min and max values, then calculate a percentage of how close they were and then return the appropriate string:
public static string GetDifferenceString(int guess, int number,
int minVal, int maxVal)
{
var percentAway =
Math.Abs(guess - number) / (double)(maxVal - minVal) * 100;
var direction = guess - number > 0 ? "High" : "Low";
if (percentAway < 10) return $"Very close, but {direction}";
if (percentAway < 20) return $"Just a little {direction}";
if (percentAway < 30) return $"Somewhat {direction}";
if (percentAway < 40) return $"Moderately {direction}";
if (percentAway < 50) return $"{direction}";
return $"Very {direction}";
}
This simplifies our main code by removing the loops and checking results from there, and lets us focus on our main tasks:
static void Main(string[] args)
{
var randomNumber = new Random().Next(1, 101);
var maxAttempts = 5;
var guess = 0;
Console.WriteLine("I'm thinking of a number between 1 and 100.");
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
Console.WriteLine($"You have {maxAttempts - attempt} " +
$"out of {maxAttempts} attempts remaining.");
guess = GetIntFromUser("Please enter your guess (1 - 100): ",
i => i > 0 && i < 101);
if (guess == randomNumber)
{
Console.WriteLine($"You have won in {attempt + 1} tries!");
break;
}
Console.WriteLine(GetDifferenceString(guess, randomNumber, 1, 100));
}
if (guess != randomNumber)
{
Console.WriteLine("Sorry, you lose! The number was: " +
$"{randomNumber}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}