Timer with questions in c# - 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);
}

Related

Local variables - switch case

I am studying programming and I am very beginner (started 2 months ago).
I am doing a c# exercise for maths calculation. Our professor used a if ... else (embricated) loops to do the exercise. I wanted to use a switch case but I am struggling with the local variables.
I understand the issue: case 2 and 3 does not "know" the variables totalNumber and nbrSubAssy is as they come from case 1 and case 2, then they are detected as not assigned.
If I still want to use a switch case, what could I do to solve it?
using System;
namespace Denombrements
{
class Program
{
static long IntMultiplication(int startValue, int endValue)
{
long multiplication = 1;
for (int k = startValue; k <= endValue; k++)
multiplication *= k;
return multiplication;
}
static int UserSelection(String message)
{
int number = 0;
Console.Write(message);
try
{
number = int.Parse(Console.ReadLine());
Console.WriteLine();
}
catch
{
Console.WriteLine();
Console.WriteLine("Wrong input, enter an integer");
}
return number;
}
static void Main(string[] args)
{
char choice = '1';
while (choice != '0')
{
Console.WriteLine("Permutation ...................... 1");
Console.WriteLine("Arrangement ...................... 2");
Console.WriteLine("Combination ...................... 3");
Console.WriteLine("Quit ............................. 0");
Console.Write("Choice : ");
choice = Console.ReadKey().KeyChar;
Console.WriteLine();
switch(choice)
{
case '0':
Environment.Exit(0);
break;
case '1':
int totalNumber = UserSelection("Total number of elements to be taken into account");
long permutation = IntMultiplication(1, totalNumber);
Console.WriteLine(totalNumber + "! = " + permutation);
break;
case '2':
int nbrSubAssy = UserSelection("Total number of elements in the subassy to be taken into account");
long arrangement = IntMultiplication(totalNumber - nbrSubAssy + 1, totalNumber);
Console.WriteLine("A(" + totalNumber + "/" + nbrSubAssy + ") = " + arrangement);
break;
case '3':
long combination = arrangement / IntMultiplication(1, nbrSubAssy);
Console.WriteLine("C(" + totalNumber + "/" + nbrSubAssy + ") = " + combination);
break;
default:
Console.WriteLine("Wrong input");
break;
}
}
Console.ReadLine();
}
}
}
Declare your variable before While loop and it will keep the value of it for all the life of LOOP and you could access the old values
char choice = '1';
int nbrSubAssy = 0;
int totalNumber = 0;
long arrangement = 0;
while (choice != '0')
{
// code ...
switch (choice)
{
case '0':
Environment.Exit(0);
break;
case '1':
totalNumber = UserSelection("Total number of elements to be taken into account");
long permutation = IntMultiplication(1, totalNumber);
Console.WriteLine(totalNumber + "! = " + permutation);
break;
case '2':
nbrSubAssy = UserSelection("Total number of elements in the subassy to be taken into account");
arrangement = IntMultiplication(totalNumber - nbrSubAssy + 1, totalNumber);
Console.WriteLine("A(" + totalNumber + "/" + nbrSubAssy + ") = " + arrangement);
break;
case '3':
long combination = arrangement / IntMultiplication(1, nbrSubAssy);
Console.WriteLine("C(" + totalNumber + "/" + nbrSubAssy + ") = " + combination);
break;
default:
Console.WriteLine("Wrong input");
break;
}
}
or in my opinion the better solution you could ask for the value in every case you need them

Running this calculator in loop in console

I am trying to make this console calculator running in loop until the user want to exit the application. How can i use a for loop with if else statements, is it possible?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Oppgave3Lesson1
{
class Program
{
static void Main(string[] args)
{
double sum = 0;
double num1;
Console.WriteLine("First number: ");
num1 = Convert.ToInt32(Console.ReadLine());
double num2;
Console.WriteLine("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
Console.WriteLine("Do you want to do an another math operation?");
Console.ReadLine();
}
}
}
You can add a question for user via Console.ReadKey method and then check his answer:
do
{
double sum = 0;
double num1;
Console.WriteLine("First number: ");
num1 = Convert.ToInt32(Console.ReadLine());
double num2;
Console.WriteLine("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.WriteLine("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
Console.WriteLine("Calculate the next operation (Y/N)?");
}
while(Console.ReadKey(true).Key == ConsoleKey.Y);
So you get the output like in the screenshot below:
Try following. I made the writlines a write :
namespace Oppgave3Lesson1
{
class Program
{
static void Main(string[] args)
{
while(true)
{
double sum = 0;
double num1;
Console.Write("First number: (or Exit)");
string firstNumStr = Console.ReadLine();
if(firstNumStr == "Exit") break;
num1 = Convert.ToInt32(firstNumStr);
double num2;
Console.Write("Second number: ");
num2 = Convert.ToInt32(Console.ReadLine());
Console.Write("Addisjon eller Subtraksjon?");
string regneoperasjon = Console.ReadLine();
if(regneoperasjon == "Subtraksjon")
{
Console.Write("Svaret til denne regneoperasjonen er: " + (sum = num1 - num2));
}
else if (regneoperasjon == "Addisjon")
{
Console.Write("Svaret til denne regneoperasjonen er: " + (sum = num1 + num2));
}
}
A for loop is used when you know the (maximum) number of iterations upfront.
In your scenario, a while loop is more apropriate.
do
{
// Perform your logic here
Console.WriteLine("Press any key to continue; Q to quit");
var key = Console.ReadKey();
}while( key != ConsoleKey.Q );
or, use an endless while - loop and break from the loop on a certain condition:
while( true )
{
// Perform your logic here
Console.WriteLine("Press any key to continue; Q to quit");
var key = Console.ReadKey();
if( key == ConsoleKey.Q )
{
break;
}
}

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();

C# variable changes value unexpectedly

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!

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.

Categories

Resources