My program is where someone is inputting temperatures until they enter 999, the temps need to be in between -20 and 130. once 999 is entered, it is supposed to calculate the total amount of temps entered and the average temperature. Im not sure where im going wrong with this code, i do have a little trouble with the loops. any help is appreciated!
static void Main(string[] args)
{
int temp = 0, total = 0, sum = 0;
double avg;
string = tempString;
WriteLine("Enter daily high temperatures, to stop program enter 999.");
tempString = ReadLine();
temp = Convert.ToInt32(tempString);
do
{
if (temp >= 20 && temp <= 130)
{
WriteLine("Enter daily high temperatures, to stop program enter 999");
ReadLine();
total++;
}
else
{
WriteLine("Valid temperatures range from -20 to 130. Please reenter temperature.");
ReadLine();
}
} while (temp != 999);
sum += temp;
avg = sum / total;
WriteLine("The number of temperatures entered: {0} /n The average temperature is: {1}.", total, avg);
}
You want to add temp to sum in your first if statement before you read the next temp. Also set temp to the next ReadLine in each if statement. Also, you had 20 in the first if statement instead of -20. Finally, add a ReadLine to the end so the console doesn't close instantly after entering 999.
static void Main(string[] args)
{
int temp = 0, total = 0, sum = 0;
double avg;
string tempString;
Console.WriteLine("Enter daily high temperatures, to stop program enter 999.");
tempString = Console.ReadLine();
temp = Convert.ToInt32(tempString);
do
{
if (temp >= -20 && temp <= 130)
{
sum += temp;
Console.WriteLine("Enter daily high temperatures, to stop program enter 999");
temp = Convert.ToInt32(Console.ReadLine());
total++;
}
else
{
Console.WriteLine("Valid temperatures range from -20 to 130. Please reenter temperature.");
temp = Convert.ToInt32(Console.ReadLine());
}
} while (temp != 999);
avg = sum / total;
Console.WriteLine("The number of temperatures entered: {0} /n The average temperature is: {1}.", total, avg);
Console.ReadLine();
}
Update your code to following -
static void Main(string[] args)
{
int temp = 0, total = 0, sum = 0;
double avg;
string tempString=string.Empty;
Console.WriteLine("Enter daily high temperatures, to stop program enter 999.");
tempString = Console.ReadLine();
temp = Convert.ToInt32(tempString);
while (temp != 999)
{
if (temp >= 20 && temp <= 130)
{
Console.WriteLine("Enter daily high temperatures, to stop program enter 999");
tempString = Console.ReadLine();
temp = Convert.ToInt32(tempString);
sum += temp;
total++;
}
else
{
Console.WriteLine("Valid temperatures range from -20 to 130. Please reenter temperature.");
Console.ReadLine();
}
}
avg = sum / total;
Console.WriteLine("The number of temperatures entered: {0} {2}The average temperature is: {1}.", total, avg,"\n");
}
Related
Having problem with my work i want to write a program that does the sum and average the student grade in the average function i used a do while loop since i want anyone to enter grade until the user enter -1 the loop end.
The problem is i do not want to run the _cal = Int32.Parse(Console.ReadLine()); in the fucntion instead run it in the main by passing a value to Average() parameter then using the value in main as a console.readlIne because i will use the user input to divide by the sum in order to get average am new to programming.
public static void Main()
{
Console.WriteLine("Please Enter the scores of your student: ");
Console.WriteLine("----------------------------------------");
_studentTotalGrade = Average();
Console.WriteLine("sum " + Sum);
Console.ReadLine();
}
public static double Average()
{
double _cal,_sumTotal = 0;
int i = 0;
do
{
_cal = Int32.Parse(Console.ReadLine());
if (_cal == -1)
{
break;
}
if (_cal > 20)
{
Console.WriteLine("Adjust score\");
continue;
}
_sumTotal +=_cal;
i--;
} while (_cal > i);
return _sumTotal;
}
}
I've only been learning C# for about a week, and I have this personal project that I am working on. I am building a program to calculate a salesperson's monthly bonus. At the end of my code, I need to tell the user the total bonus amount and the bonus cannot exceed $230.
My question is, how do I retrieve the user inputs to get a total and how do I set a limit of $230?
Any help will be appreciated.
I tried using more if statements to retrieve what the user already input.
Console.WriteLine("What is the total number of items sold?");
int itemsSold = Convert.ToInt16(Console.ReadLine());
int itemBonus = 50;
if (itemsSold > 20)
{
Console.WriteLine("Your items sold bonus is {0} dollars" ,itemBonus);
}
else
Console.WriteLine("You have not sold enough items to recieve the item bonus");
Console.WriteLine("What is the total dollar value of all items sold?");
int bonus1 = 100;
int bonus2 = 200;
int dollarValue = Convert.ToInt16(Console.ReadLine());
double totalEarned1 = (dollarValue * bonus1 + itemBonus);
double totalEarned2 = (dollarValue * bonus2 + itemBonus);
if (dollarValue >= 1000 && dollarValue < 5000)
{
Console.WriteLine("You have recieved a bonus of {0} ", bonus1);
}
else if (dollarValue >= 5000)
{
Console.WriteLine("You have recieved a bonus of {0} ", bonus2 );
}
else
{
Console.WriteLine("You have not recieved a dollar value bonus");
}
Console.ReadLine();
You have to refactorize your code. Since if the user did not sell more than 20 items, it is of no use to continue the calculation:
Console.WriteLine("What is the total number of items sold?");
int itemsSold = Convert.ToInt16(Console.ReadLine());
int itemBonus = 50;
if (itemsSold > 20)
{
int bonus1 = 100;
int bonus2 = 200;
Console.WriteLine("Your items sold bonus is {0} dollars" ,itemBonus);
Console.WriteLine("What is the total dollar value of all items sold?");
int dollarValue = Convert.ToInt16(Console.ReadLine());
double totalEarned1 = (dollarValue * bonus1 + itemBonus);
double totalEarned2 = (dollarValue * bonus2 + itemBonus);
totalEarned1 = Math.Max( totalEarned1, 230 );
totalEarned2 = Math.Max( totalEarned2, 230 );
if (dollarValue >= 1000 && dollarValue < 5000)
{
Console.WriteLine("You have recieved a bonus of {0} ", bonus1);
}
else if (dollarValue >= 5000)
{
Console.WriteLine("You have recieved a bonus of {0} ", bonus2 );
}
else
{
Console.WriteLine("You have not recieved a dollar value bonus");
}
}
else {
Console.WriteLine("You have not sold enough items to recieve the item bonus");
}
Console.ReadLine();
Hope this helps.
I'm new to C#, and i'm writing a do while loop that continues to ask the user to enter "price", until they enter "-1" for price.
Afterwards, I need to add up all the values for price they entered and declare that as the subtotal.
The problem I have is that it only remember the last number entered, which would be -1. What would I have to do to fix this?
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal;
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
} while (price != -1);
subtotal = Convert.ToInt32(price);
Console.Write("Subtotal: ${0}", subtotal);
}
}
}
Try this variation to Artem's answer. I think this is a little cleaner.
int count = 0;
decimal input = 0;
decimal price = 0;
while (true)
{
Console.Write("Item {0} Enter Price: ", count++);
input = Convert.ToDecimal(Console.ReadLine());
if (input == -1)
{
break;
}
price += input;
}
In each iteration of the loop, you overwrite the value of price. Separate input and storage price.
decimal input = 0;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
input = Convert.ToDecimal(Console.ReadLine());
if (input != -1)
price += input;
} while (input != -1);
Use a list and keep adding the entries to the list.
Or you can keep a running total in another integer.
Something like:
int total = 0; // declare this before your loop / logic other wise it will keep getting reset to 0.
total = total+ input;
Please try to use this
using System;
namespace ConsoleApp1
{
class Program
{
static void Main()
{
Console.WriteLine("Your Receipt");
Console.WriteLine("");
Console.WriteLine("");
decimal count;
decimal price;
decimal subtotal = 0m; //subtotal is needed to be initialized from 0
decimal tax;
decimal total;
count = 1;
do
{
Console.Write("Item {0} Enter Price: ", count);
++count;
price = Convert.ToDecimal(Console.ReadLine());
if (price != -1) //if the console input -1 then we dont want to make addition
subtotal += price;
} while (price != -1);
//subtotal = Convert.ToInt32(price); this line is needed to be deleted. Sorry I didnt see that.
Console.Write("Subtotal: ${0}", subtotal); //now subtotal will print running total
}
}
}
here i ask the user for homework scores which are then averaged after discarding the smallest and largest score. i have stored the user input in an array. in my DisplayResults method im not sure how to display the lowest and highest scores that were discarded. any help is appreciated! Here is what i have so far:
class Scores
{
static void Main(string[] args)
{
double sum = 0;
double average = 0;
int arraySize;
double[] inputValues;
arraySize = HowManyScores();
inputValues = new double[arraySize];
GetScores(inputValues);
sum = CalculateSum(inputValues);
average = CaculateAverage(sum, arraySize);
DisplayResults(inputValues, average);
Console.Read();
}
public static int HowManyScores()
{
string input;
int size;
Console.WriteLine("How many homework scores would you like to enter?");
input = Console.ReadLine();
while (int.TryParse(input, out size) == false)
{
Console.WriteLine("Invalid data. Please enter a numeric value.");
input = Console.ReadLine();
}
return size;
}
public static void GetScores(double[] inputValues)
{
double scoreInput;
Console.Clear();
for (int i = 0; i < inputValues.Length; i++)
{
scoreInput = PromptForScore(i + 1);
inputValues[i] = scoreInput;
}
}
public static double PromptForScore(int j)
{
string input;
double scoreInput;
Console.WriteLine("Enter homework score #{0}:", j);
input = Console.ReadLine();
while (double.TryParse(input, out scoreInput) == false)
{
Console.WriteLine("Invalid Data. Your homework score must be a numerical value.");
input = Console.ReadLine();
}
while (scoreInput < 0)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
while (scoreInput > 10)
{
Console.WriteLine("Invalid Data. Your homework score must be between 0 and 10.");
input = Console.ReadLine();
}
return scoreInput;
}
public static double CalculateSum(double[] inputValues)
{
double sum = 0;
for (int i = 1; i < inputValues.Length - 1; i++)
{
sum += inputValues[i];
}
return sum;
}
public static double CaculateAverage(double sum, int size)
{
double average;
average = sum / ((double)size - 2);
return average;
}
public static void DisplayResults(double[] inputValues, double average)
{
Console.Clear();
Console.WriteLine("Average homework score: {0}", average);
//Console.WriteLine("Lowest score that was discarded: {0}",
//Console.WriteLine("Highest score that was discarded: {0}",
}
}
}
You basically only have to do one thing: Sorting the array after you received your input data. Then, printing the first and last value gives you the minimal and maximal score. Use
Array.Sort(intArray);
in main after calling GetScores and
Console.WriteLine("Lowest score: {0} Highest score: {1}",
inputValues[0], inputValues[inputValues.Length - 1]);
to print the results. Cheers
EDIT: The proposal by Jens from the comments using the Min/Max is probably more what you're looking for if you're not interested in complete ordering of your values.
The requirement are:
create an application that will allow the user to enter numbers and
provide the average of the numbers entered. The user will be allowed to enter as many numbers as they choose. After each entry we will display the current average.
Keep repeating until the user decides to quit.
I want to user to keep entering number until they type "q" to quit. Please help.
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
total += Convert.ToInt32(input);
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
while (input.ToUpper() == "Q");
{
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
Console.ReadKey();
Put the Console.ReadLine inside the loop -- and put the writing of the total/average after calculating those numbers.
Also, you might want to validate the input, instead of assuming it is a number -- use int.TryParse.
do
{
Console.WriteLine("Enter a number of Q to quit", input);
input = Console.ReadLine();
int val;
if (int.TryParse(input, out val))
{
total += val;
average = (total / numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered++, average);
}
}
while (input.ToUpper() != "Q");
There are three points needs to be corrected.
numbersEntered is 0 in the first calculation. You should pre-increment it while dividing by it.
also in the condation of while loop, it should be input.ToUpper() != "Q" instead of input.ToUpper() == "Q".
After correcting above two things your current code is calculating the average but it clearing the console after printing it. So, you should want after printing it by Console.Read();
Following is the code corrected:
string input = "";
int numbersEntered = 0;
int average = 0;
int total = 0;
do
{
Console.Clear();
Console.WriteLine("Enter a number or Q to quit", input);
input = Console.ReadLine();
int valueEntered;
if (int.TryParse(input, out valueEntered))
{
total += valueEntered;
average = (total / ++numbersEntered);
Console.WriteLine("Total: {0}\t Numbers Entered: {1}\t Average: {2}\t", total, numbersEntered, average);
Console.ReadKey();
}
}
while (input.ToUpper() != "Q");
Console.WriteLine("Press any key to continue");
Console.ReadKey();
Simply a typo(?) Your while needs to be:
...
while (input.ToUpper() != "Q");
That is != instead of ==.
Minimalistic solution:
int nTotal = 0;
double avg = 0;
string input;
while ((input = Console.ReadLine()).ToUpper() != "Q")
{
int number = int.Parse(input);
avg += (number-avg) / ++nTotal;
Console.WriteLine("Total numbers entered: {0}. Average: {1}", nTotal, avg);
}