C# variable changes value unexpectedly - c#

The title basically says it all. The variable "answer" in my code randomly changes value to another random number when it is defined.
The program is supposed to ask ten random maths questions and tell the user if they have got the correct answer or not, however this doesn't seem to be working at all.
Once the variable has changed, the program then also asks about 3 more questions, and tells the user the answer to each is incorrect.
static void Main(string[] args)
{
Random R = new Random();
double solution = 0;
string sign = "";
int score = 0;
for (int i = 0; i < 10; i++)
{
int X = R.Next(1, 5);
int Y = R.Next(1,10);
int Z = R.Next(1,10);
switch (X)
{
case 1:
solution = Y + Z;
sign = "+";
break;
case 2:
solution = Y - Z;
sign = "-";
break;
case 3:
solution = Y / Z;
sign = "/";
break;
case 4:
solution = Y * Z;
sign = "X";
break;
}
Console.WriteLine("What is " + Y + " " + sign + " " + Z + "?");
double answer = Console.Read();
if (answer == solution)
{
Console.WriteLine("Correct");
score = score + 1;
Console.Read();
}
else if (answer != solution)
{
Console.WriteLine("Incorrect. The correct answer is " + solution);
Console.Read();
}
else
{
Console.WriteLine("Error");
Console.Read();
}
}
}
}
}

Your problem is in Console.Read(). This will return the characters number. Starting at 48 (0x30) for character 0. That's why all of your answers are incorrect.
So I suggest you use Console.ReadLine() and then parse the string to answer.
double answer;
if (!double.TryParse(Console.ReadLine(), out answer))
{
Console.WriteLine("Error");
continue;
}
if (answer == solution)
{
Console.WriteLine("Correct");
score = score + 1;
}
else if (answer != solution)
{
Console.WriteLine("Incorrect. The correct answer is " + solution);
}

The problem is that you are using Console.Read() which returns only the next character code. Instead, you should use Console.ReadLine(). Also after you check the answers you use some unnecessary Console.Read()(s). I have removed them and this code is working perfectly fine: -
static void Main(string[] args)
{
Random R = new Random();
double solution = 0;
string sign = "";
int score = 0;
for (int i = 0; i < 10; i++)
{
int X = R.Next(1, 5);
int Y = R.Next(1,10);
int Z = R.Next(1,10);
switch (X)
{
case 1:
solution = Y + Z;
sign = "+";
break;
case 2:
solution = Y - Z;
sign = "-";
break;
case 3:
solution = Y / Z;
sign = "/";
break;
case 4:
solution = Y * Z;
sign = "X";
break;
}
Console.WriteLine("What is " + Y + " " + sign + " " + Z + "?");
double answer = double.Parse(Console.ReadLine());
if (answer == solution)
{
Console.WriteLine("Correct");
score = score + 1;
}
else if (answer != solution)
{
Console.WriteLine("Incorrect. The correct answer is " + solution);
}
}
}
Another thing is that the division questions are actually integer divisions. If you want decimals instead, you should use something like solution = Math.Round((double)((decimal)Y / (decimal)Z), 3); to check a value rounded to 3 decimal places.

I think your problem lies in the fact that Console.Read returns an integer code for the last character pressed (see https://msdn.microsoft.com/en-us/library/system.console.read(v=vs.110).aspx for details).
You need code something like this:
double answer = double.Parse(Console.ReadLine());
This takes the entire input (which might be more than one character) and converts it to a double (Console.ReadLine returns a string) so you are comparing like with like.

Console.Read();
returns an int value(The ASCII code) and you are storing this as answer which is of type double ! Use
Console.ReadLine();
instead ! Also you need to convert your answer to a double value to be able to compare your answer to the solution!

Related

My simple prog was repeating, I looked it over and over again...what happened? [duplicate]

This question already has answers here:
Why does Read interfere with ReadLine? [duplicate]
(1 answer)
why getting null value from console in c# for readLine() after using read()
(1 answer)
Flushing System.Console.Read()
(3 answers)
Closed 1 year ago.
So, I am refreshing myself on C#. I decided to write a simple calculator program and was showing my daughter. I added a while loop to my main and added an if statement to break the loop if the user doesn't want to repeat the process...I added some methods for the operators and added some info at the end. After that it stopped repeating and just totally skips getting input from the "x = (char)Console.Read();" line and exits. Helpful advice would be appreciated, I am still a beginner with coding so please don't criticize me, thanks. Full code below:
using System;
namespace TrueCalculator
{
class Program
{
public static int addition(int num1, int num2)
{
int result = num1 + num2;
return result;
}
public static int subtraction(int num1, int num2)
{
int result = num1 - num2;
return result;
}
public static int division(int num1, int num2)
{
int result = num1 / num2;
return result;
}
public static int multiplication(int num1, int num2)
{
int result = num1 * num2;
return result;
}
static void Main(string[] args)
{
char x = 'y';
while (x == 'y' || x == 'Y')
{
Console.WriteLine("\t\t\tTrue Calculator\n\t\t Only uses whole numbers!\n\t\t ***BETA VERSION***");
Console.WriteLine("Enter first number: ");
int num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter second number: ");
int num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Please type desired operator to perform: +, -, /, *");
char op = (char)Console.Read();
if (op == '+')
{
Console.WriteLine(num1 + " + " + num2 + " = " + addition(num1, num2));
}
else if (op == '-')
{
Console.WriteLine(num1 + " - " + num2 + " = " + subtraction(num1, num2));
}
else if (op == '/')
{
Console.WriteLine(num1 + " / " + num2 + " = " + division(num1, num2));
}
else if (op == '*')
{
Console.WriteLine(num1 + " * " + num2 + " = " + multiplication(num1, num2));
}
Console.WriteLine("Reset, y/n?");
x = Convert.ToChar(Console.Read());
if (x == 'n' || x == 'N')
{
break;
}
}
Console.WriteLine("\n\n\t\t\tThank you for using True Calculator\n\nDeveloped by Duster_2015..." +
"\nAny comments or suggestions send to: " +
"FIXME: Enter your Duster email.");
Console.ReadKey();
}
}
}
(This applies to Windows which uses \r\n for newlines. Other systems use only \n.)
When the program asks you to enter "+, -, /, *" and you type
+enter
three chars are put into the console's buffer:
+\r\n
These chars sit there until you read them (or flush them). When you do
char op = (char)Console.Read();
Only one of those chars is read. The variable op is assigned to '+' and the + is removed from the console's input buffer, but the buffer still has
\r\n
in it - just waiting to be read.
Then when you do
x = Convert.ToChar(Console.Read());
it sees the \r in the buffer and it is read immediately - you don't get a chance to type anything and x is assigned '\r'. When the loop rolls back to the beginning, (x == 'y' || x == 'Y') is false and it ends.
One solution is to not use Console.Read() and use Console.ReadLine() instead. This reads the entire input buffer - up to and including the next \n - but neither the \r nor the \n are included in the result. Then you can use string comparisons:
string op = Console.ReadLine();
if (op == "+")....
If you want to use char instead, you need to check for blank strings:
string op = Console.ReadLine();
if (!String.IsNullOrEmpty(op)) {
if (op[0] == '+') ....

c# (beginner) how to make a short version of this "if" code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I just learned how to use if and tried to do a simple calculator. but the code is way too long and i want to add more options to it, can i make it any shorter using any other method?
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many numbers do you wish to calculate? ");
string HowMany = Console.ReadLine();
if (HowMany == "2") {
Console.Write("Enter #1: ");
int x = int.Parse(Console.ReadLine());
Console.Write("Enter #2: ");
int y = int.Parse(Console.ReadLine());
int sum = x + y; int sub = x - y; int mult = x * y; int div = x / y;
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div); }
else if (HowMany == "3") {
Console.Write("Enter #1: ");
int x = int.Parse(Console.ReadLine());
Console.Write("Enter #2: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter #3: ");
int z = int.Parse(Console.ReadLine());
int sum = x + y + z; int sub = x - y - z; int mult = x * y * z; int div = x / y / z;
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div); }
else if (HowMany == "4")
{
Console.Write("Enter #1: ");
int x = int.Parse(Console.ReadLine());
Console.Write("Enter #2: ");
int y = int.Parse(Console.ReadLine());
Console.Write("Enter #3: ");
int z = int.Parse(Console.ReadLine());
Console.Write("Enter #4: ");
int w = int.Parse(Console.ReadLine());
int sum = x + y + z + w; int sub = x - y - z - w; int mult = x * y * z * w; int div = x / y / z / w;
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div);
}
Console.ReadKey();
}
}
}
This does just the sum. I'll leave handling the other calculations to you.
int sum = 0;
for(int i = 1;i<=HowMany;i++)
{
Console.Write("Enter #{0}: ", i);
int input = int.Parse(Console.ReadLine());
sum += input;
}
Console.WriteLine("The Result : Sum = {0}", sum);
using System.IO;
using System;
class Program {
static void Main() {
Console.WriteLine("How many numbers do you wish to calculate? ");
string HowMany = Console.ReadLine();
int[] nums = new int[int.Parse(HowMany)];
int sum = 0, sub = 0, mult = 1, div = 1;
for (int i = 0; i < int.Parse(HowMany); i++) {
Console.Write("Enter #" + (i + 1) + ": ");
nums[i] = int.Parse(Console.ReadLine());
sum += nums[i];
sub -= nums[i];
mult *= nums[i];
div /= nums[i];
}
Console.WriteLine("The Result : Sum = " + sum + " Sub = " + sub + " Mult = " + mult + " Div = " + div);
Console.ReadKey();
}
}
You can just use a loop, and keep a rolling total of the values. Also, I changed div to be a double, because integer division is really boring - it's nice to see the decimal value:
I also made it so the user can only enter an integer greater than zero for the quantity of numbers they want to calculate.
And finally, they can only enter a non-zero integer for the number, because a zero input means we have to do some check for that during division, the multiplication value will always be zero, and it does nothing to the addition and subtraction totals.
Console.Write("How many numbers do you wish to calculate? ");
int count;
while (!int.TryParse(Console.ReadLine(), out count) || count < 1)
{
Console.Write("Error: enter a positive, whole number: ");
}
int input, sum = 0, sub = 0, mult = 0;
double div = 0;
for (int i = 1; i <= count; i++)
{
Console.Write($"Enter #{i}: ");
// Don't allow user to enter 0. It does nothing to the addition or subtraction
// values, will make the multiplication value zero, and cannot be use for division
while (!int.TryParse(Console.ReadLine(), out input) || input == 0)
{
Console.Write("Error: enter a non-zero whole number: ");
}
if (i == 1)
{
// On the first input, we just store the number
sum = sub = mult = input;
div = input;
}
else
{
sum += input;
sub -= input;
mult *= input;
div /= input;
}
}
Console.WriteLine("The Result : Sum = " + sum + " Sub = " +
sub + " Mult = " + mult + " Div = " + div);
Console.ReadKey();

Timer with questions in c#

I have a cosole appliction
in this try to set timer that is when question display then timer should be start and when in 10 seconds answer not give then should start next question i want to do this
i am done with
I set 3 conditions first they should type number that how many question want to attemppt then select level then select operator .. so when all question typed i.e.
no of question : 2
level : 1
operator: +
then timer start of 10 seconds and when 10 seconds complete then question is display
where as i want first question display and timer then when question not answered with in 10 seconds then next should start
this is what i do
class Program
{
static void Main(string[] args)
{
Random rnd = new Random();
int userans;
int computerans;
int numofquestions;
int numofquestionsleft;
int correctanswer = 0;
Console.WriteLine("\t\t OPERATOR OF QUIZ \t\t");
Console.WriteLine("\t\tOperator 1:Addition(+)\t\t");
Console.WriteLine("\t\tOperator 2:Subtarction(-)\t\t");
Console.WriteLine("\t\tLEVELS OF QUIZ\t\t");
Console.WriteLine("\t\tLevel 1 (1-9)\t\t");
Console.WriteLine("\t\tLevel 2 (10-99)\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.WriteLine("\t\tYour quiz start now\t\t");
Console.WriteLine("\t\t-------------------\t\t");
Console.Write("How many questions do you want to attempt? ");
numofquestions = Convert.ToInt32(Console.ReadLine());
Console.Write("Which level that you want to play? ");
int level = Convert.ToInt32(Console.ReadLine());
Console.Write("which operator do you want to play?");
string opt = Console.ReadLine();
//for (int a = 10; a >= 0; a--)
//{
// Console.SetCursorPosition(0, 2);
// Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
// System.Threading.Thread.Sleep(1000);
//}
numofquestionsleft = numofquestions;
while (numofquestionsleft > 0)
{
if (level == 1)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(1, 10);
int num2 = rnd.Next(1, 10);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(1, 10);
num2 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(1, 10);
int num4 = rnd.Next(1, 10);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(1, 10);
num4 = rnd.Next(1, 10);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
if (level == 2)
{
switch (opt)
{
case "+":
{
int num1 = rnd.Next(10, 99);
int num2 = rnd.Next(10, 99);
Console.Write("What is the sum of " + num1 + " and " + num2 + "? ");
computerans = num1 + num2;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num1 = rnd.Next(10, 99);
num2 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
case "-":
{
int num3 = rnd.Next(10, 99);
int num4 = rnd.Next(10, 99);
Console.Write("What is the subtraction of " + num3 + " and " + num4 + "? ");
computerans = num3 - num4;
userans = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("The correct answer is\n" + computerans);
Console.WriteLine("Your answer is \n" + userans);
if (computerans == userans)
{
Console.WriteLine(" Congratulation your answer is correct!\n");
correctanswer++;
}
else
{
Console.WriteLine(" Sorry your answer is wrong! Try again.\n");
}
numofquestionsleft--;
num3 = rnd.Next(10, 99);
num4 = rnd.Next(10, 99);
Console.WriteLine("Your correct answer are " + correctanswer + " out of attempt" + numofquestions + " question");
break;
}
}
}
//if(numofquestions>)
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(1000);
}
Console.ReadKey();
}
}
}
}
Your code is quite messy. You got everything in a single method. So creating additional method(s), which a timer needs, you cannot access any variable that is important to the timer. You need to start making your own classes. This gives you so much more control over the variables of your program. It is difficult with your code, to put you in the right direction. You need to change so much.
For fun, and some experience as well, I created what you was working on. A calculating game, or test, or w/e you wanna call it. I will share my code with you, in the hope you will learn some things out of it.
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Program
{
static void Main(string[] args)
{
// Add different difficulty options
Dictionary<string, Difficulty> DifficultyOptions = new Dictionary<string, Difficulty>();
DifficultyOptions.Add("easy", new EasyDifficulty());
DifficultyOptions.Add("medium", new MediumDifficulty());
DifficultyOptions.Add("hard", new HardDifficulty());
// Add different game options
Dictionary<string, GameType> GameOptions = new Dictionary<string, GameType>();
GameOptions.Add("additive", new GameAdditive());
GameOptions.Add("subtractive", new GameSubtractive());
GameOptions.Add("randomize", new GameRandomize());
// Default game settings at start up
string GameDiff = "easy";
string GameMode = "additive";
Console.WriteLine("Welcome to Verkade's Calculating Game.");
Console.WriteLine("By default game difficulty has been set to " + GameDiff);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of DifficultOptions variable, and display them
foreach (KeyValuePair<string, Difficulty> kvp in DifficultyOptions)
{
Console.WriteLine("/difficulty " + kvp.Key);
}
Console.WriteLine("");
Console.WriteLine("By default game mode has been set to " + GameMode);
Console.WriteLine("Type in the following commands to change that:");
// This will take out all possible options out of game options and display them
foreach (KeyValuePair<string, GameType> GameTypes in GameOptions)
{
Console.WriteLine("/gamemode " + GameTypes.Key);
}
Console.WriteLine("");
Console.WriteLine("When you're done setting up, type in /start to start the game,");
Console.WriteLine("/stop to stop the game. /exit to stop entirely.");
//This will keep the instance of the game once started
Game CurrentGame = null;
//this will keep the program alive. By typing /exit, it will turn into false, and stops the program.
bool KeepProgramAlive = true;
//This is a loop that keeps on listening to your input
while (KeepProgramAlive)
{
// This will split up the users input, when a space is used.
// This way the first cut will contain /start, /stop, /gamemode, etc. It will be stored as 'UserInput[0]'
// In the second cut, which is 'UserInput[1]', things like 'easy', 'medium', 'hard', 'subtractive', etc will be stored
string[] UserInput = Console.ReadLine().Split(' ');
switch (UserInput[0])
{
case "/exit":
{
KeepProgramAlive = false;
break;
}
case "/start":
{
if (DifficultyOptions.ContainsKey(GameDiff) && GameOptions.ContainsKey(GameMode))
{
Console.WriteLine("Game has been set up. When you're ready, press Enter so you'll get your first question");
CurrentGame = new Game(DifficultyOptions[GameDiff], GameOptions[GameMode]);
}
break;
}
case "/stop":
{
if (CurrentGame != null)
{
CurrentGame.Stop();
CurrentGame = null;
Console.WriteLine("Game has been stopped. You can not change settings and start again if you like.");
}
break;
}
case "/gamemode":
{
// checking the length to see there are 2 values. /gamemode is 1 of them. 'subtractive' is another one.
if (UserInput.Length >= 2)
{
// very important, because i am using a dictionary, i can check whether the gamemode exists or not
if (GameOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed gamemode to " + UserInput[1]);
GameMode = UserInput[1];
}
else
{
Console.WriteLine("That gamemode does not exist");
}
}
break;
}
case "/difficulty":
{
if (UserInput.Length >= 2)
{
if (DifficultyOptions.ContainsKey(UserInput[1]))
{
Console.WriteLine("You have changed the difficulty to " + UserInput[1]);
GameDiff = UserInput[1];
}
else
{
Console.WriteLine("That difficulty does not exist");
}
}
break;
}
default:
{
// checking if the game has started, and if so, Handler in the game-class will check your input
if (CurrentGame != null)
{
int NumberGiven;
Int32.TryParse(UserInput[0], out NumberGiven);
CurrentGame.Handler(NumberGiven);
}
break;
}
}
}
}
}
}
Operators.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
abstract class GameType
{
public int Answer;
public Random Rnd = new Random();
public abstract string MakeSum(Difficulty Diff);
}
class GameAdditive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
}
class GameSubtractive : GameType
{
public override string MakeSum(Difficulty Diff)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
class GameRandomize : GameType
{
public override string MakeSum(Difficulty Diff)
{
int mode = Rnd.Next(0, 2);
if (mode == 0)
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 + num2;
return num1 + " + " + num2;
}
else
{
int num1 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber) + Diff.MaxNumber;
int num2 = Rnd.Next(Diff.MinNumber, Diff.MaxNumber);
Answer = num1 - num2;
return num1 + " - " + num2;
}
}
}
}
Game.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using System.Threading.Tasks;
namespace CalculatingGame
{
class Game
{
Difficulty Game_Diff;
GameType Game_Type;
int TicksRemaining = 0;
int TotalAnswers = 0;
int CorrectAnswers = 0;
int WrongAnswers = 0;
Timer TimerCountdown;
public Game(Difficulty GDiff, GameType GType)
{
Game_Diff = GDiff;
Game_Type = GType;
TimerCountdown = new Timer(100);
TimerCountdown.Elapsed += TimerCD;
TimerCountdown.AutoReset = true;
}
public void Handler(int Answer)
{
if (TicksRemaining > 0)
{
if (Answer == Game_Type.Answer)
{
CorrectAnswers++;
Console.WriteLine("Good job. You got the correct answer.");
}
else
{
WrongAnswers++;
Console.WriteLine("Wrong answer. The answer was " + Game_Type.Answer + ".");
}
TotalAnswers++;
Console.WriteLine("Current score: " + CorrectAnswers + " correct answers out of " + TotalAnswers);
TicksRemaining = 0;
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
else
{
string SumText = Game_Type.MakeSum(Game_Diff);
Console.WriteLine("What is the solution to the sum " + SumText);
TicksRemaining = Game_Diff.Time;
TimerCountdown.Start();
}
}
public void TimerCD(Object source, ElapsedEventArgs e)
{
if(TicksRemaining > 0)
{
TicksRemaining--;
if ((TicksRemaining % 10) == 0)
{
Console.Write(Math.Floor((decimal)(TicksRemaining / 10)) + "...");
}
if (TicksRemaining == 0)
{
WrongAnswers++;
Console.WriteLine("\r\nTime is up. The answer was " + Game_Type.Answer);
Console.WriteLine("Press Enter to get your new sum.");
TimerCountdown.Stop();
}
}
}
public void Stop()
{
TimerCountdown.Stop();
}
}
}
Difficulty.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalculatingGame
{
// nice thing about abstract classes and child classes are that you can store a 'EasyDifficulty' object under variable-type 'Difficulty'
// this allows me to create a dictionary, with 'Difficulty' type as value, and yet put all the different child classes in there
// another thing you can do, and you can see it under 'Operators.cs' file, is that you can have a method, with the same name in every
// child class, and yet they perform different things.
abstract class Difficulty
{
public int MinNumber = 1;
public int MaxNumber = 1;
// Time in ticks. 1 tick = 100ms. Reason why I made it so is because maybe you want to give the player 7.5 seconds to do the sum
public int Time = 100;
}
class EasyDifficulty : Difficulty
{
public EasyDifficulty()
{
MinNumber = 1;
MaxNumber = 9;
Time = 100;
}
}
class MediumDifficulty : Difficulty
{
public MediumDifficulty()
{
MinNumber = 1;
MaxNumber = 99;
Time = 75;
}
}
class HardDifficulty : Difficulty
{
public HardDifficulty()
{
MinNumber = 1;
MaxNumber = 999;
Time = 50;
}
}
}
Your delay is only 1 second. Increase the delay to 10 seconds by:
for (int a = 10; a >= 0; a--)
{
Console.SetCursorPosition(0, 2);
Console.Write("Generating Preview in {0} ", a); // Override complete previous contents
System.Threading.Thread.Sleep(10000);
}

C# Console Output Formatting

I'm trying to get a factorial to be displayed as for example (factorial of 5 is 5*4*3*2*1)
I'm using a method for the factorial, but it doesn't accept the line Console.Write(i + " x "); in my code.
Any help would be great.
here is my code.
//this method asks the user to enter a number and returns the factorial of that number
static double Factorial()
{
string number_str;
double factorial = 1;
Console.WriteLine("Please enter number");
number_str = Console.ReadLine();
int num = Convert.ToInt32(number_str);
// If statement is used so when the user inputs 0, INVALID is outputed
if (num <= 0)
{
Console.WriteLine("You have entered an invalid option");
Console.WriteLine("Please enter a number");
number_str = Console.ReadLine();
num = Convert.ToInt32(number_str);
//Console.Clear();
//topmenu();
//number_str = Console.ReadLine();
}
if (num >= 0)
{
while (num != 0)
{
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
}
Console.Write(i + " x ");
Console.Clear();
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
factorial = 1;
Console.WriteLine("(please any key to return to main menu)");
Console.ReadKey();
Console.Clear();
topmenu();
}
}
return factorial;
}
Thank you!
The problem is that your for loop isn't using braces, so the scope is just one line.
Try adding braces appropriately:
for (int i = num; i >= 1; i--)
{
factorial = factorial * i;
Console.Write(i.ToString() + " x ");
}
Console.WriteLine("factorial of " + number_str.ToString() + " is " + factorial);
Without the braces, the i variable only exists on the next statement (factorial = factorial * i;), and no longer exists in scope by the time you call Console.Write.
You will likely also want to remove the call to Console.Clear immediately following this Write, or you will not see it.
here's a solution to consider
public static void Main()
{
Console.WriteLine("Please enter number");
int input;
while (!int.TryParse(Console.ReadLine(), out input) || input <= 0)
{
Console.WriteLine("You have enter an invald option");
Console.WriteLine("Please enter number");
}
Console.Write("Factorial of " + input + " is : ");
int output = 1;
for (int i = input; i > 0; i--)
{
Console.Write((i == input) ? i.ToString() : "*" + i);
output *= i;
}
Console.Write(" = " +output);
Console.ReadLine();
}
int.TryParse() will be beneficial for you, so the program doesn't crash if the user inputs a non-integer
also, you may want something besides an integer. Factorials get very large very fast - anything over 16 will return a wrong result.

Ask user for starting and stopping point within the array?

In C# how do i ask user for starting and stopping point within the array?
Below is my code so far:
class Program
{
static void Main(string[] args)
{
double[] num = { 10, 20, 30, 40, 50 };
double n = num.Length;
Console.Write("Elements of, arrary are:" + Environment.NewLine);
for (int i = 0; i < n; i++)
{
Console.WriteLine(num[i]);
}
double sum = 0;
for (int i = 0; i < n; i++)
{
sum = sum + num[i];
}
Console.WriteLine("The sum of elements:" + sum);
Console.ReadKey();
}
}
You'll take the sum of the elements between starting and stopping point, as I guess. Take two inputs from the user and assign them to starting and ending points to the for-loop. Such as:
int startingPoint = Convert.ToInt32(Console.ReadLine());
int endingPoint = Convert.ToInt32(Console.ReadLine());
for(int i = startingPoint; i <= endingPoint; i++)
{
//take sum etc.
}
Don't forget to inform the user about the element values in the array and what input value they are entering at that moment.
Another important thing here is to control the inputs. They should be numeric and between 0-n, starting point should be smaller than ending point.
For numeric control you can write like follows:
if (int.TryParse(n, out startingPoint))
{
// operate here
}
else
{
Console.WriteLine("That's why I don't trust you, enter a numeric value please.");
}
startingPoint should be between 0-n and cannot be n. To control it:
if (startingPoint >= 0 && startingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between 0 and " + n + ".");
}
After taking startingPoint successfully, you should control if endingPoint. It should be between startingPoint-n. After controlling for being numeric you can write as follows:
if (endingPoint >= startingPoint && endingPoint < n)
{
// operate here
}
else
{
Console.WriteLine("Please enter a number between " + startingPoint + " and " + n + ".");
}
I don't know what can I explain more for this question. Please let me know for further problems.
If you want to prompt the user for the start and end indexes:
Console.WriteLine("Please enter start index");
string startIndexAsString = Console.ReadLine();
int startIndex = int.Parse(startIndexAsString);
Console.WriteLine("Please enter end index");
string endIndexAsString = Console.ReadLine();
int endIndex = int.Parse(endIndexAsString);
var sum = num.Skip(startIndex).Take(endIndex - startIndex + 1).Sum();

Categories

Resources