I'm new to C#, well, coding in general.
I have done fairly well by myself to date, in this introduction course I am taking, but I ran into a road bump.
I am trying to figure out how to code a if statement that will run inside a loop to analyze 5 different ints as they are entered and to put the max int and min int seperatly so that I can ue the remaining three ints to make a calculation.
To be exact, validate user input and remove the min/max user input to average the remaining three.
PS, I tried an array but for some reason it wasn't working well. I don't have the code as I'm at work right now though. I was told in a lecture that an if statement should be used but arrays are possible too.
Thank you for your time and any possible answers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city, value;
double rating, avg = 0;
double[] array1 = new double[5];
double max = 0;
double min = double.MaxValue;
double score, totalScore = 0;
//get basic information
do
{
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
value = Console.ReadLine();
score = Convert.ToDouble(value);
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
array1[s] = Convert.ToDouble(score); //----this line keeps throwing an exception
}
Console.ReadLine();
//calculate totalScore by dropping min/max scores and averaging them times dive rating
foreach (int i in array1)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
totalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", totalScore);
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
}
}
}
or you can go list route and
List<int> apples = new List<int>();
apples.Add(31);
apples.Add(34);
apples.Add(100);
apples.Add(57);
apples.Add(1);
int min = apples.Min();
int max = apples.Max();
apples.Remove(min);
apples.Remove(max);
decimal average = (decimal)(apples.Sum()) / apples.Count;
Not sure about your question... You want to know, the max and min about 5 values, and the avarage about the three others...
int[] n = { 4, 7, 29, 3, 87 };
int max = 0;
int min = int.MaxValue;
double avg = 0;
foreach (int i in n)
{
if (i > max)
max = i;
if (i < min)
min = i;
avg += i;
}
avg = avg / n.Count - 2;
try this code:
int[] a = new int[5];
int minpos;
int maxpos;
int min = Int32.MaxValue;
int max = a[0];
int temp = 0;
for (int i = 0; i < 5; i++)
{
Console.WriteLine(" Enter number " + (i + 1));
Int32.TryParse(Console.ReadLine(), out temp);
a[i] = temp;
//Decision Making Logic
if (min > temp)
{
min = temp;
minpos = i;
}
if (max < temp)
{
max = temp;
maxpos = i;
}
}
//At the end of this loop you will see that minpos contains the index of minimum element
//and maxpos contains index of maximum element,values in remaining indeces contain elements that are neither max or min in that //collection
Thanks guys, it appears I needed a good night of sleep. Thanks a ton for all these helpful answers as I'm sure I will be delving into those methods soon and it will be good to be able to get a head start on them. Here is my code,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string userIsFinished = "";
string name, city;
double rating, avg = 0;
double max = 0;
double min = 10;
double score, value = 0, totalScore = 0, finalScore = 0;
//get basic information
do
{
Console.WriteLine("\n");
Console.WriteLine("Please enter divers name.");
name = Console.ReadLine();
Console.WriteLine("Please enter the divers city.");
city = Console.ReadLine();
//get and validate user input for 1 dive rating
Console.WriteLine("Please enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
while (rating < 1 || rating > 1.69)
{
Console.WriteLine("Oops, you entered an invalid number. Please, enter a dive rating between 1.00 and 1.67.");
rating = Double.Parse(Console.ReadLine());
}
Console.ReadLine();
// get and validate user input for 5 judge scores
for (int s = 1; s <= 5; s++)
{
Console.WriteLine("Please enter the score for judge {0}.", s);
score = Convert.ToDouble(Console.ReadLine());
while (score < 0 || score > 10)
{
Console.WriteLine("Invalid entry, please enter a number in between 0 - 10.");
score = Convert.ToDouble(Console.ReadLine());
}
if (score > max)
max = score;
if (score < min)
min = score;
totalScore = score + totalScore;
}
Console.ReadLine();
\\Calculate values
value = totalScore - max - min;
avg = value / 3;
finalScore = avg * rating;
//Print gathered and calculated information
Console.WriteLine("Divers name: {0}", name);
Console.WriteLine("Divers city: {0}", city);
Console.WriteLine("Dive degree of difficulty: {0}", rating);
Console.WriteLine("Total dive score is: {0}", finalScore);
Console.WriteLine("\n");
// Ask if user wants to process another diver and continue or exit program
Console.WriteLine("Would you like to enter another divers information? [Y]es [N]o: ");
userIsFinished = Console.ReadLine();
}
while
(userIsFinished.ToLower() != "n");
Console.ReadLine();
Console.WriteLine("\n");
}
}
}
Related
Console.WriteLine(" **************************************");
Console.WriteLine(" ****** Reviewer Awarding Points ******");
Console.WriteLine(" **************************************");
Console.WriteLine();
string[]properties= { "Clarity", "Orginality", "Difficulty" };
int[] a = new int[3];
int[] b = new int[3];
for(int i = 0; i < 3; i++)
{
Console.WriteLine(" ***" + properties[i]+"***");
Console.Write(" Alice: ");
a[i] = Convert.ToInt16(Console.ReadLine());
if(a[i]>100 || a[i] < 1)
Console.Write(" Bob: ");
b[i] = Convert.ToInt16(Console.ReadLine());
Console.WriteLine();
}
Console.Read();
}
I want user to enter a value between 1 and 100(including 1 and 100).So what I am gonna do?
your question is not clear
try
int value;
do{
Console.Write("Enter a value");
value=int.parse(Console.ReadLine());
}while(value<1 || value>100);
Make a method that checks the result for being in range:
public int AskInt(string question, int min, int max){
while(true){
Console.WriteLine(question);
string input = Console.ReadLine();
if(int.Tryparse(input, out int value) && value >= min && value <= max)
return value;
}
}
The only way to escape the loop is to enter a valid number that is in range, otherwise the question just repeats
Then you can use it multiple times in your code:
int age = AskInt("Enter an age between 10 and 100: ", 10, 100);
int weight = AskInt("Enter a weight between 100 and 350: " 100, 350);
Try this:
if(a[i]>=100 || a[i] <= 1)
You can learn about C# operators at this site: https://www.w3schools.com/cs/cs_operators.php
Struggling with understanding the while loop. I'm just starting to learn programming. While testing the code, it appears as if only the second number entered gets processed into the final answer.
static void Main(string[] args)
{
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = Double.Parse(input);
double sum = 0.0;
int counter = 1;
int total = 3;
while (counter < total)
{
sum = sum + value;
counter = counter + 1;
Console.WriteLine("Enter another test score");
input = Console.ReadLine();
value = Double.Parse(input);
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
}
You need your while loop to run three times so start the counter from 0 instead of 1.
Within the loop you can ask for the test scores and add them to the sum and then increment the counter.
double sum = 0.0;
int counter = 0;
int total = 3;
while (counter < total)
{
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);
sum += value;
counter++;
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
Or like this if you need the question to be different, you can ask the question outside of the loop and save the result to the sum variable. Since we have already asked the question once we can make the counter start at 1 instead of 0.
double sum = 0.0;
Console.WriteLine("Enter test score");
string input = Console.ReadLine();
double value = double.Parse(input);
sum = sum + value;
int counter = 1;
int total = 3;
while (counter < total)
{
Console.WriteLine("Enter another test score");
input = Console.ReadLine();
value = double.Parse(input);
sum += value;
counter++;
}
Console.WriteLine("Test score average is: {0:N2}", sum / total);
Console.Read();
You use Wrong number
total is 3, but you need repeat 3 times calculate
counter 1 calculate clear
counter 2 calculate clear
but counter 3 is while false.
you need to fix counter <=total or counter started 0
I am trying to make a factorial calculator in C#, but I am having difficulties taking the product of all the numbers after I have collected them into a list.
List<int> myList = new List<int>();
Console.WriteLine("My Job is to take the factorial of the number you give");
Console.WriteLine("What is the number?");
string A = Console.ReadLine();
int C = Convert.ToInt32(A);
T:
myList.Add(C);
C--;
if (C == 0) goto End;
goto T;
End:
// This is where the problem is,
// i don't know of a way to take to product of the list "myList"
//Any Ideas?
int total = myList.product();
Console.WriteLine(" = {0}", total);
Console.ReadLine();
You don't need a list to do a factorial:
Console.WriteLine("My Job is to take the factorial of the number you give");
Console.WriteLine("What is the number?");
int c = Convert.ToInt32(Console.ReadLine());
int total = 1;
for (int i = 2; i < c; i++)
{
total *= i;
}
Console.WriteLine(total.ToString());
Console.ReadLine();
There doesn't seem to be much benefit in adding all the numbers to a list unless you need that for something.
As an alternative, something like this should work:
// set product to the number, then multiply it by every number down to 1.
private int GetFactorial(int number)
{
int product = number;
for (var num = number - 1; num > 0; num--)
{
product *= num;
}
return product;
}
This Console Application is Supposed to Display Prices and then set it in a average format and in a Less than NUM and Higher then NUM which I am entirely confused. The total and the Average come Out to the right amount just not the lessthanfive and the higherthanaverage.
CODE:
double[] prices = new double[5];
int count = 0;
double TotalValues = 0;
double Average = 0;
string inputString;
double lessthanfive = 0;
double higherthanaverage = 0;
int x;
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
Average = TotalValues / prices.Length;
if (prices[x] < 5)
lessthanfive++;
if (prices[x] > Average)
higherthanaverage++;
}
Console.WriteLine();
Console.WriteLine("The Sum of The Values Are: {0}", TotalValues.ToString("C2"));
Console.WriteLine("Numbers Less Than $5.00 Are: {0}", lessthanfive.ToString("C2"));
Console.WriteLine("The Average of The 20 Prices Are: {0}", Average.ToString("C2"));
Console.WriteLine("Numbers Higher then Average Are: {0}", higherthanaverage.ToString("C2"));
Console.ReadLine();
You can't know the average until after the last value has been entered, so you need another loop to count the number of items above the average:
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
if (prices[x] < 5) {
lessthanfive++;
}
}
Average = TotalValues / prices.Length;
for (x = 0; x < prices.Length; x++)
{
if (prices[x] > Average) {
higherthanaverage++;
}
}
Your average is going to be wrong, and your counts are going to be off because of it. Calculating everything outside of that loop will keep things easy to debug, as well. Now, this isn't the most elegant solution out there, but it uses a List to leverage the built-in Sum and Average functions, as well as allowing your list to be re-sizable, in case you don't want to add 20 numbers each time.
List<decimal> prices = new List<decimal>();
int numPrices;
decimal totalPrice;
decimal averagePrice;
string inputString;
int lessThanFive = 0;
int higherThanAverage = 0;
Console.Write("Enter the number of prices that you will be entering: ");
numPrices = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < numPrices; i++)
{
Console.Write("Enter the price for item #{0}: $", i+1);
inputString = Console.ReadLine();
prices.Add(Convert.ToDecimal(inputString));
}
totalPrice = prices.Sum();
averagePrice = prices.Average();
foreach (decimal item in prices)
{
if (5 > item)
{
lessThanFive++;
}
if (averagePrice > item)
{
higherThanAverage++;
}
}
Console.WriteLine();
Console.WriteLine("The sum of the values are: {0:C}", totalPrice);
Console.WriteLine("The number of prices less than $5.00 are: {0}", lessThanFive);
Console.WriteLine("The average of the prices entered is: {0:C}", averagePrice);
Console.WriteLine("The number of prices that are higher than average are: {0}", higherThanAverage);
Console.ReadLine();
Now, I used decimal instead of double for these because, well, in this example it certainly wouldn't need a double for anything, but it could be converted back without any problems. Also added some minor string formatting, etc. The main thing is, I checked the math and it works.
The average is calculated in the wrong scope (inside the loop) and so is the higherthanaverage. To fix it:
class Program
{
static void Main(string[] args)
{
double[] prices = new double[5];
int count = 0;
double TotalValues = 0;
double Average = 0;
string inputString;
double lessthanfive = 0;
double higherthanaverage = 0;
int x;
for (x = 0; x < prices.Length; x++)
{
count += 1;
Console.Write("Enter the price for {0}: ", count);
inputString = Console.ReadLine();
prices[x] = Convert.ToDouble(inputString);
TotalValues += prices[x];
if (prices[x] < 5)
lessthanfive++;
}
Average = prices.Average();
higherthanaverage = prices.Where(price => price > Average).Count();
Console.WriteLine();
Console.WriteLine("The Sum of The Values Are: {0:C2}", TotalValues);
Console.WriteLine("Numbers Less Than $5.00 Are: {0:C2}", lessthanfive);
Console.WriteLine("The Average of The 20 Prices Are: {0:C2}", Average);
Console.WriteLine("Numbers Higher then Average Are: {0:C2}", higherthanaverage);
Console.ReadLine();
}
}
Basically I've created a times table app. At the end of the app, I've been able to say how many times I got it wrong, and how many times I got it right.
However I want it to say:
You got:
6 x 4 wrong 6 times.
5 x 2 wrong 9 times.
etc...
Rather than you got 20 correct, and 8 wrong.
So I can see the specific multiplications I got wrong. I know where I need to add the code (under the else statement). But not sure how to go about this.
I thought the best solution would be storing all the wrongs as a string in an array, then counting identical strings and outputting a number. But I have no idea how to do this.
Here's my code:
namespace TimesTablesGame
{
class multiplication
{
Random rng = new Random();
int randomNumber;
int randomNumberTables;
int c = 0;
int w = 0;
int numberOfGos = 0;
int minRangeTables;
int maxRangeTables;
int minRange;
int maxRange;
public multiplication()
{
start:
Console.Clear();
Console.WriteLine("\nPlease enter the lowest number range you would like to practice your times tables on: ");
minRangeTables = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the higest number range you would like to practice your times tables on: ");
maxRangeTables = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the number of times you would like play: ");
numberOfGos = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the minimum range you would like to multiply by: ");
minRange = int.Parse(Console.ReadLine());
Console.WriteLine("\nPlease enter the maximum range you would like to multiply by: ");
maxRange = int.Parse(Console.ReadLine());
repeat:
Console.Clear();
for (int i = 1; i <= numberOfGos; i++)
{
randomNumberTables = rng.Next(minRangeTables, maxRangeTables + 1);
randomNumber = rng.Next(minRange, maxRange + 1);
Console.Write("\n\n{0}: {1} x {2} = ", i, randomNumberTables, randomNumber);
if (randomNumberTables * randomNumber == int.Parse(Console.ReadLine()))
{
Console.WriteLine("Correct");
c++;
}
else
{
Console.WriteLine("Wrong it is: " + randomNumberTables * randomNumber);
w++;
}
}
Console.WriteLine("\nYou were correct {0} times, and wrong {1} times.", c, w);
Console.ReadLine();
Console.WriteLine("Would you like to play again? Type y for Yes with new settings, r for repeat using last settings, and any other key to exit.");
char again = Console.ReadKey().KeyChar;
if (again == 'y')
{
c = 0;
w = 0;
goto start;
}
else if (again == 'r')
{
c = 0;
w = 0;
goto repeat;
}
}
}
}
I'd keep track in a Dictionary....
Resisting the urge to re-write the GOTO stuff.....here's a relatively simple way to do it:
Dictionary<string, int> wrongs;
//Console questions...
//Begin looping logic
wrongs = new Dictionary<string, int>();
for (int i = 1; i <= numberOfGos; i++)
{
randomNumberTables = rng.Next(minRangeTables, maxRangeTables + 1);
randomNumber = rng.Next(minRange, maxRange + 1);
string eq = String.Format("{0} x {1} = ", randomNumberTables, randomNumber);
Console.Write("{0}: " + eq, i);
if (randomNumberTables * randomNumber == int.Parse(Console.ReadLine()))
{
Console.WriteLine("Correct");
c++;
}
else
{
Console.WriteLine("Wrong it is: " + randomNumberTables * randomNumber);
if (wrongs.Any(x => x.Key == eq))
{
wrongs[eq]++;
}
else
{
wrongs.Add(eq, 1);
}
w++;
}
}
Console.WriteLine("\nYou were correct {0} times, and wrong {1} times.", c, w);
Console.WriteLine("\n\nYou got:");
foreach (var item in wrongs)
{
Console.WriteLine("{0} wrong {1} times", item.Key, item.Value);
}
//Your logic to repeat/restart
Also....note that this does not count "2 x 4" and "4 x 2" as the same equation....
Also also....You can easily do this without using GOTO....please consider it.