What I want to do is have random numbers be generated and take those random numbers and put them through a modulus operator. And I want it to ask the user for the answer they think it is and then they will be told if it is right or wrong. This is what I have.
Random rand = new Random();
int minA;
int maxA;
int minB;
int maxB;
int usersAnswer;
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out minA);
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out maxA);
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out minB);
Console.WriteLine("what is the minimum value: ");
Int32.TryParse(Console.WriteLine(), out maxB);
Console.WriteLine("What is the result of {0} % {1}? ", rand.Next(minA, maxA), rand.Next(minB, maxB));
Int32.TryParse(Console.ReadLine(), out usersAnswer);
answer = //directly implementing the random numbers generated with modulous operator)
if(userAnswer == answer)
{
Console.WriteLine("{0} is correct", answer);
}
else
{
Console.WriteLine("Good try, but no: {the random number} % {the other random number} = {0}", not sure, not sure, answer)
}
So what I want to know is how I can directly implement the random numbers already generated from "Console.WriteLine("What is the result of {0} % {1}? ", rand.Next(minA, maxA), rand.Next(minB, maxB));" into a modulus operator equation and get the answer.
I hope this all made sense
You should store your 2 random numbers as new variables in your class:
int RandomOne;
int RandomTwo;
assign them further down
RandomOne = rand.Next(minA, maxA);
RandomTwo = rand.Next(minA, maxA);
and then refer to them in your messaging. Something like:
Console.WriteLine($"What is the result of {RandomOne} % {RandomTwo}?");
Your code have some promblem:
Remember to fix your instructions text
Somthimes, you use writeline(),but readline() actually
You should handle that something might be going wrong, check comment out
Try it
static void Main(string[] args)
{
Random rand = new Random();
int minA, maxA;
int minB, maxB;
int userAnswer;
Console.WriteLine("what is the minimum A: ");
if (!Int32.TryParse(Console.ReadLine(), out minA)) { return; } //If something going wrong, you should handle it.
Console.WriteLine("what is the maximum A: ");
if (!Int32.TryParse(Console.ReadLine(), out maxA)) { return; }
Console.WriteLine("what is the minimum B: ");
if (!Int32.TryParse(Console.ReadLine(), out minB)) { return; }
Console.WriteLine("what is the maximum B: ");
if (!Int32.TryParse(Console.ReadLine(), out maxB)) { return; }
if (minA > maxA) { exchange(ref minA, ref maxA); } //User might have typo,and this is one way to fix it.
if (minB > maxB) { exchange(ref minB, ref maxB); }
int rndA = rand.Next(minA, maxA),
rndB = rand.Next(minB, maxB); //You should restore the random result, or lost it
int result;
try
{
result = calcMod(rndA, rndB); //Directly implementing the random numbers generated with modulous operator
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return;
}
Console.WriteLine($"What is the result of {rndA} % {rndB}? ");
Int32.TryParse(Console.ReadLine(), out userAnswer);
if (userAnswer == result)
{
Console.WriteLine("{0} is correct", result);
}
else
{
Console.WriteLine($"Good try, but no: {rndA} % {rndB} = {result}");
}
Console.Write("\nPress Any key to leave.");
Console.ReadKey();
}
//Calculate mod result
static int calcMod(int i1, int i2)
{
try
{
return i1 % i2;
}
catch (Exception e)
{
throw e;
}
}
//Swap number
static void exchange(ref int i1, ref int i2)
{
int tmp;
tmp = i1;
i1 = i2;
i2 = tmp;
}
Related
I am currently working on a program that is a loop with a sentinel value that asks the user to enter a number or enter -99 to end the program and it runs perfectly. If I were to change that -99 to just the word "Quit" is there a certain parameter that I would have to put? For example, if I want to use a letter, I know that I could use:
char (undefined parameter) = 'A'
But how would I do this with a word? When I simply try to change the value of -99 to Quit, I receive an error as expected.
using System;
class Program {
public static void Main (string[] args) {
int sum = 0;
int counter = 0;
int max = Int32.MinValue;
int min = Int32.MaxValue;
bool keepGoing = true;
while(keepGoing) {
Console.WriteLine("Please enter a number or enter -99 to stop the program:");
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
sum += number;
if (number >= max) {
max = number;
}
if (number <= min) {
min = number;
}
}
}
double average = (double) sum / counter;
Console.WriteLine($"{counter} numbers were entered.");
Console.WriteLine("The average is:" + average);
Console.WriteLine("The sum is:" + sum);
Console.WriteLine("The maximum value is:" + max);
Console.WriteLine("The minimum value is:" + min);
}
}
It's difficult to store "Quit" in an int, so the root of your problem is that you have no separation between pulling the string from the console and converting it to an int:
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
If you did have a separation, it becomes possible:
string input = Console.ReadLine();
if (input == "Quit"){
keepGoing = false;
} else {
int number = Convert.ToInt32(input);
counter++;
A user enters two prime numbers which are then multiplied together, and another calculation of (a-1) * (b-1) is completed (a and b being the prime numbers entered). a function to checks the numbers entered, if the numbers are NOT prime, the user will be asked to re-enter the numbers. However, when I test this, I've noticed that if the user inputs a number which ISN'T prime, and then re-enters a prime number, the calculations are based on the number which ISN'T prime. E.g. if the user enters 2 and 4, since 4 isn't prime they are asked to enter another number, e.g 3, the calculations will be based on the numbers 2 and 4.
How can I correct this so it takes the valid prime number and not the invalid number originally entered?
namespace example
{
class Program
{
class Co_P
{
static void coprime(ref int c, int calculation)
{
if (gcd(c, calculation) == 1)
Console.WriteLine("it's Co-Prime");
else
do
{
Console.WriteLine("it isn't Co-Prime");
Console.WriteLine("Enter a Co-Prime");
c = int.Parse(Console.ReadLine());
coprime(ref c, calculation);
} while (gcd(c, calculation) != 1);
}
static int Prime_a(int a) //check a is prime
{
if (a <= 1) return 0;
for (int i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
return 0; //not prime
}
}
return 1;
}
static void result(int a) //outputs if a is prime/or not
{
if (Prime_a(a) != 0)
{
Console.WriteLine(a + " is a prime number");
}
else do
{
Console.WriteLine(a + " isn't prime number");
Console.WriteLine();
Console.WriteLine("Please make sure you enter a prime number");
a = int.Parse(Console.ReadLine());
} while (Prime_a(a) == 0);
}
static int Prime_b(int b)
{
if (b <= 1) return 0;
for (int i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return 0;
}
}
return 1;
}
static void resultb(int b)
{
int result = Prime_b(b);
if (Prime_b(b) != 0)
{
Console.WriteLine(b + " is a prime number");
}
else do
{
Console.WriteLine(b + " is not a prime number");
Console.WriteLine("Please make sure you enter a prime number");
b = int.Parse(Console.ReadLine());
} while (Prime_b(b) == 0);
}
static void Main(string[] args)
{
int a;
Console.WriteLine("Enter a prime number for a");
a = int.Parse(Console.ReadLine());
Console.WriteLine();
result(a);
Console.WriteLine();
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
int total = a * b;
Console.WriteLine("The total of the prime numbers is = " + total);
int calculation = (a - 1) * (b - 1); //calculation
Console.WriteLine();
Console.WriteLine("The result = " + calculation);
Console.WriteLine();
}
}
}
You should extend result and resultb function so it returns new prompted valid number
static int result(int a) {
var result = Prime_a(a);
if (result != 0)
...code...
return result
}
Also don't forget to reassign those values
...code...
a = result(a);
...code...
b = resultb(b);
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
In line resultb(b); you are passing int to method resultb. int is a value type, or in other words, passing int to a method means passing its value to a method, where copy of that value is created. In this case a copy of b is created in method resultb. Every further change on b inside method resultb is made on copy and original stays the same.
In resultb method pass parameter by reference by adding ref keyword. Instead
static void resultb(int b)
{
// code
}
method will look like this
static void resultb(ref int b)
{
// code
}
You will call the method this way
resultb(ref b);
Here's the portion of code.
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(ref b);
Console.WriteLine();
Now every change on passed b inside method resultb will reflect on the original.
You should do the same for method result(int a).
I have written a guess the number game between 1-100.
This is my code..
class Program
{
static void Main(string[] args)
{
while (true)
{
int randno = Newnum(1, 101);
int count = 1;
while (true)
{
Console.Write("Guess a number between 1 and 100, or press 0 to quit: ");
int input = Convert.ToInt32(Console.ReadLine());
if (input == 0)
return;
else if (input < randno)
{
Console.WriteLine("Unlucky, that number is too low - have another go!");
++count;
continue;
}
else if (input > randno)
{
Console.WriteLine("Unlucky, that number is too high - have another go!");
++count;
continue;
}
else
{
Console.WriteLine("Well done - you guessed it! The number was {0}.", randno);
Console.WriteLine("It took you {0} {1}.\n", count, count == 1 ? "attempt" : "attempts to guess it right");
break;
}
}
}
}
static int Newnum(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
}
How can I edit it so that if a user gets close to the number, say within 5 numbers, they are greeted with a message saying they're close?
You can use Math.Abs:
int diff = Math.Abs(input - randno);
if(diff <= 5)
{
// say him that he's close
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
This code works when I enter 10 values. If I enter less my sentinel value is added. I'd like that to stop, as well as being able to manipulate my array length so I don't get however many 0's left when entering less than 10.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace IntegerStatistics
{
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[10];
int arrayCount, high, low, sum;
double avg;
arrayCount = FillArray(numbers);
Statistics(numbers, arrayCount, out high, out low, out sum, out avg);
for (int x = 0; x < numbers.Length; ++x)
Write("{0, 4}", numbers[x]);
WriteLine();
WriteLine("The array has {0} values", arrayCount);
WriteLine("The highest value is {0}", high);
WriteLine("The lowest value is {0}", low);
WriteLine("The sum of the array is {0}", sum);
WriteLine("The average is {0}", avg);
}
private static int FillArray(int[] numbers)
{
const int QUIT = 999;
string enterNum;
int stop;
int count = 0;
int addNum = 0;
stop = numbers.Length - 1;
while((addNum != QUIT) && (count <= stop))
{
Write("Enter a number or 999 to exit: ");
enterNum = ReadLine();
while (!int.TryParse(enterNum, out numbers[count]))
{
WriteLine("Error");
Write("Enter a number or 999 to exit: ");
enterNum = ReadLine();
}
numbers[count] = Convert.ToInt32(enterNum);
addNum = numbers[count];
++count;
}
return count;
}
private static int Statistics(int[] numbers, int arrayCount, out int high, out int low, out int sum, out double avg)
{
high = numbers.Max();
low = numbers.Min();
sum = numbers.Sum();
avg = numbers.Average();
return arrayCount;
}
}
}
First, let's fix your code, because it is very simple: rather than using numbers.Length in the Main, use arrayCount. This is something that you already have, and it will stop Main from showing zeros at the end.
I'd like [...] to manipulate my array length
Although .NET provides a way to resize an array, this is not something you should be doing in general, because your code quickly becomes hard to read.
A better solution to this problem would be to return a properly sized array from FillArray. However, the best solution is to switch to using List<T>, which are allowed to grow and shrink as needed.
I have modified your original program to use a List<int> (good practice) instead of an array of integers which is dynamically re-sized (no so good practice, in general).
class Program
{
static void Main(string[] args)
{
// Use a collection instead of an array, as length is as of yet unknown:
List<int> numbers;
int high, low, sum;
double avg;
numbers = FillArray();
Statistics(numbers, out high, out low, out sum, out avg);
foreach (var number in numbers)
{
Console.Write("{0, 4}", number);
}
Console.WriteLine();
Console.WriteLine("The array has {0} values", numbers.Count);
Console.WriteLine("The highest value is {0}", high);
Console.WriteLine("The lowest value is {0}", low);
Console.WriteLine("The sum of the array is {0}", sum);
Console.WriteLine("The average is {0}", avg);
Console.ReadKey();
}
private static List<int> FillArray(int maximum = 10)
{
const int QUIT = 999;
int count = 0;
int addNum = 0;
var list = new List<int>();
while (count <= maximum)
{
Console.Write("Enter a number or 999 to exit: ");
if (!int.TryParse(Console.ReadLine(), out addNum))
{
Console.WriteLine("Error");
continue;
}
if (addNum == QUIT)
{
break;
}
list.Add(addNum);
count++;
}
return list;
}
private static void Statistics(List<int> numbers, out int high, out int low, out int sum, out double avg)
{
high = numbers.Max();
low = numbers.Min();
sum = numbers.Sum();
avg = numbers.Average();
}
}
I also noticed you were including your "escape" value of 999 with your collection of numbers. I corrected this so that 999 is not included with the calculated average (I am guessing that was your intention).
Similar to #Dave. Allows for a value of 999. There's no exception handling, tho...
class Program
{
private static string _STOP = "STOP";
private static int _MAX_SIZE = 10;
static void Main(string[] args)
{
List<int>numbers = FillList();
foreach(int number in numbers)
Console.Write("{0, 4}", number);
Console.WriteLine();
Console.WriteLine("The list has {0} values", numbers.Count);
Console.WriteLine("The highest value is {0}", numbers.Max());
Console.WriteLine("The lowest value is {0}", numbers.Min());
Console.WriteLine("The sum of the array is {0}", numbers.Sum());
Console.WriteLine("The average is {0}", numbers.Average());
Console.ReadKey();
}
private static List<int> FillList()
{
List<int> numbers = new List<int>();
int value;
int count = 0;
do
{
Console.Write("Enter a number or {0} to exit: ", _STOP);
string line = Console.ReadLine();
if (line == _STOP)
break;
if (int.TryParse(line, out value))
{
numbers.Add(value);
count++;
}
else
{
Console.WriteLine("Error reading number.");
}
} while (count < _MAX_SIZE);
return numbers;
}
}
I am new to programming and I think I have confused myself I'm trying to make a loop that asks users for integers when the user inputs a integer greater than 100 then the console displays the amount of integers the user has input and the sum of these integers. I know it's basic but I can't figure where I went wrong.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum1, strNum2;
int num1, num2;
int i = 0;
int sum =0 ;
Console.WriteLine("Please enter a integer between 1 and 100"); // asks for user input
strNum1 = Console.ReadLine();
num1 = int.Parse(strNum1);
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum2 = Console.ReadLine();
num2 = int.Parse(strNum2); //input is stored as num2
sum = num2; //store num2 in sum
i++;
if (num2 >= 100) // if num2 int is greater than 100
{
sum = (num1 +num2 +sum); // do calculation
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
while (i < 100);
}
}
}
any help would be appreciated thanks everyone!
You're on the right track... a couple of things:
Do... While is used when you always want to run through the block at least once, so your first 'get' from the user can be inside the block. You can code whatever you want to happen after the condition fails right after the block, instead of checking the same condition inside it.
Make sure if you're simply using Parse that you wrap it in a try...catch, because your user could type in anything (not just numbers). Personally I usually use TryParse instead.
Finally, make sure you're comparing to the correct variable. Checking that i < 100 will keep looping until 100 numbers have been entered; you want to compare the user's input instead.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string prompt = "Please enter {0} integer between 1 and 100";
string strNum;
int num = 0;
int i = 0;
int sum =0 ;
do //ask once and repeat while 'while' condition is true
{
string pluralPrompt = i > 0 ? "another" : "an";
prompt = string.Format(prompt,pluralPrompt);
Console.WriteLine(prompt); // asks for user input
strNum = Console.ReadLine();
if (!Int32.TryParse(strNum, out num)) //input is stored as num
{
// warn the user, throw an exception, etc.
}
sum += num; //add num to sum
i++;
}
while (num < 100);
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
}
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum;
int num;
int i = 0;
int sum = 0;
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum = Console.ReadLine();
if (int.TryParse(strNum, out num)) //input is stored as num2
{
if (num < 101)
{
i++;
sum += num;
continue;
}
else
{
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
break;
}
}
}
while (i < 100);
}
}