A few weeks ago I began studying a c# beginners course, I got stuck on Arrays.
I do not want the complete answer for my problem, I want the tools or links to figure it out of myself
I´am trying to make a console Application that acts like a "Weather Station".
The program should take user input as an array on how many measurements have been made (Done). After that the user will enter the degrees in an loop (Done)
The program should write out all the measurements and the average measurement.
I can calculate the average but don't know how to print the results
I've come this far...
Console.WriteLine("How many measurements have you done");
string str = Console.ReadLine();
int size = Convert.ToInt32(str);
int[] temperatur = new int[size];
for (int i = 0; i < temperatur.Length; i++)
{
Console.WriteLine("Enter temperature " + i + ": ");
str = Console.ReadLine();
int element = Convert.ToInt32(str);
temperatur[i] = element;
}
Console.WriteLine("");
int sum = 0;
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " +
sum / temperatur.Length);
Seeing as you state that the only problem you are having is 'print out all the measurements', all you have to do is add an additional Console.WriteLine() to the existing for loop you already have. You will also to have to add braces. As such:
int sum = 0;
for (int i = 0; i < temperatur.Length; i++){
sum = sum + temperatur[i];
Console.WriteLine("Measurement {0} is {1}", i+1, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
You might not recognise that Console.WriteLine(), but it's basically a neat way of formatting your output using placeholders. The {0} will be replaced with the first value provided, the {1} with the second.
EDIT: MSDN documentation on Console.WriteLine() and also String.Format
for (int i = 0; i < temperatur.Length; i++)
sum = sum + temperatur[i];
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Change this to :
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0} is {1}", i, temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
If you want to do it in the same for:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
Console.WriteLine("Temperature {0}", temperatur[i]);
}
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
In another statement:
for (int i = 0; i < temperatur.Length; i++)
{
sum = sum + temperatur[i];
}
temperatur.ForEach(x => Console.WriteLine("Temperature {0}", x));
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
...
Console.WriteLine("The average temperature is " + sum / temperatur.Length);
Console.ReadLine();
In the end type Console.ReadLine();
Related
I am trying to output the overall class average on a test using a program which makes use of arrays. The program is meant to be for a class of 12 students. When I try to input all data I need, I don't get the average for the class as a whole. The problem obviously lies in the average calculator itself but seeing as I am a beginner I have little clue how to fix it. Any help would be appreciated. Just to reiterate, I am looking for a solution on how to fix my average calculator to give the class average as an overall. I have entered my code below. I hope I have been specific.
string[] studentnames = new string[12];
int[] testscore = new int[12];
int i;
int index;
double average;
int total = 0;
//title
Console.Write("\n\nStudent lists:\n");
Console.Write("******************\n");
//asks user to input names
Console.Write("Enter student names:\n");
for (i = 1; i < 12; i++)
{
Console.Write("Student name {0} : ", i);
studentnames[i] = (Console.ReadLine());
//asks user to enter student's test score
Console.Write("Please enter their test score: ");
testscore[i] = Convert.ToInt32(Console.ReadLine());
}
//outputs all values user has entered
Console.WriteLine("\nStudent marks: ");
for (i = 1; i < 12; i++)
{
Console.WriteLine("Name: ");
Console.WriteLine("{0} ", studentnames[i]);
Console.WriteLine("Test score: ");
Console.WriteLine("{0} ", testscore[i]);
}
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
Console.ReadKey();
The division by the total needs to be after the for loop.
This:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
average = total / 12;
Console.WriteLine("The class average was: " + average);
}
Needs to become:
for (index = 1; index < 12; index++)
{
total = total + testscore[index];
}
average = ((double)total) / 12;
Console.WriteLine("The class average was: " + average);
Another problem: your for loops start at index 1. C# uses 0 based indexing. I assume you are trying to calculate the average for 12 students, not 11.
Also, for the love of god please stop writing the number 12. If you absolutely must hard-code it, use a constant.
Edit: I've updated my answer to account for flydog's comment
I have been trying to make a program that you input a number and i keeps asking for numbers untill their sum has reached the number and displays how many numbers it took. the problem i'm facing is that if the last number makes it over the input number it still counts it while it should stop.
static void Main(string[] args)
{
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = 0;`
while (sum < sumLimit)
{
int number = Convert.ToInt32(Console.ReadLine());
sum += number;
count++;
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
}
Here's one option to fix it, depending on your expected result you can let the count start at -1 or 0:
int sumLimit = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int count = -1;
int number = 0;
while (sum + number < sumLimit)
{
sum += number;
count++;
number = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine(sum + " " + count);
Console.ReadLine();
The problem I have is that when I enter an element from the array, the user input resets to the start of the loop, for example when i user input the third element from the array, the user input question two more times to continue to the next user input question, how can I fix this? everybody know what I can adjust here.
worked loop image with 1st element entered
looping error
while (true)
{
String[] bgtype = { "cheeseburger","tlc", "bbq" };
int[] bgtypeprice = { 15, 25, 10 };
int max = bgtype.Length;
String[] product = new string[max];
String[] type = new string[max];
int[] qty = new int[max];
int[] disc = new int[max];
Console.WriteLine("");
for (int i = 0; i < max; i++)
{
Console.Write("What PRODUCT would you like to buy ?: "); ;
product[i] = Console.ReadLine();
if (product[i].Equals("burger", StringComparison.CurrentCultureIgnoreCase))
{
{
Console.Write("What TYPE of product would you like to buy?: ");
type[i] = Console.ReadLine();
if (bgtype[i].Contains(type[i]))
{
Console.Write("Enter your discount % (5% for adults & 7% for minors): ");
disc[i] = Convert.ToInt32(Console.ReadLine());
Console.Write("How many will you buy? ");
qty[i] = Convert.ToInt32(Console.ReadLine());
float total = bgtypeprice[i]; total *= qty[i];
Console.WriteLine("Total cost of " + type[i] + " " + product[i] + " is: " + qty[i] + " pieces x P" + bgtypeprice[i] + "= P" + total);
float totaldisc = 0; totaldisc = (total * disc[i]) / 100;
Console.WriteLine("Total amount of discount: P " + totaldisc);
float totalamt = 0; totalamt = total - totaldisc;
Console.WriteLine("Total cost of order: P " + totalamt);
Console.WriteLine("-------------------ORDER CONFIRMATION-------------------");
}}}}}
if (bgtype[i].Contains(type[i])) should be changed to if (bgtype.Contains(type[i]))
Array.Contains, verifies if an item is contained within an Array, not an Array value. By asking if bgtype[i] contains type[i], you are asking if cheesburger contains tlc, which it doesn't, hence why it starts from the beginning. By verifying if bgtype contains type[i], you are asking if ["cheesburger", "tlc", "bbq"] contains tlc, which it does. I hope this was clear enough.
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();
}
}
Hi, I am trying to add the sum of the random numbers in my random number gen to get the average of the random numbers that were generated also to display them in a message box. I can not do arrays. Here is what I have so far:
class Program
{
static double average = 0;
static double sum = 0;
static void Main(string[] args)
{
Random number = new Random();
int min = int.MaxValue, max = int.MinValue;
string result = "\tn \n";
for (int counter = 0; counter < 100; counter++)
{
int n = number.Next(0, 1000);
// Console.WriteLine(n);
if (n < min)
min = n;
if (n > max)
max = n;
}
sum = sum + (number.Next()) ;
average = sum / 100;
int range = min - (min + 1);
result += " \t"
+ min
+ " \t"
+ max
+ " \t"
+ average
+ " \t"
+ sum
+ " \t"
+ range;
MessageBox.Show(result, "Min = {0}, Max = {1}, Range = {2}");
}
I would like a hint to solve this problem not a list of code that is just given to me. Thank you.
You'll want to put this inside of the for loop:
sum = sum + n;
(or sum += n;)
Then after the loop, the average will be the sum divided by 100.
Also you can take out the min and max part, unless that is needed for something else.