❔ c# hw help
Write an application named DailyTemps that continuously prompts a user for a series of daily high temperatures until the user enters a sentinel value of 999. Valid temperatures range from -20 through 130 Fahrenheit. When the user enters a valid temperature, add it to a total; when the user enters an invalid temperature, display the error message:
Valid temperatures range from -20 to 130. Please reenter temperature
Before the program ends, display the number of temperatures entered and the average temperature.
using System;
using static System.Console;
class DailyTemps
{
static void Main()
{
// Write your main here.
}
}
im just really lost here and need help on pretty much this whole problem. if anyone can help at all i'd appreciate it very much!
5 Replies
We aren't going to do your homework for you - you should at least try writing some code and if you get stuck you can ask specific questions and someone can help.
fr 💀
some clues:
- use a
List<float>
to store the temperatures entered
- use a while(true)
loop to keep collecting temperatures from the user
- use $tryparse to parse the string that the user enters into a float
- do the logic and display the reuslts after the loopThe TryParse pattern is considered best practice of parsing data from a string:
- a TryParse method returns
true
or false
to inform you if it succeeded or not, so you can use it directly in a condition,
- since C# 7 you can declare a variable that will be used as an out
argument inline in an argument list,
- it forces you to check if the out
argument contains valid data afterwards,
Avoid: Convert.ToInt32 — it's a bad choice for parsing an int
. It exists only for backwards compatibility reasons and should be considered last resort. (Note: Convert does contain useful conversion methods: To/FromBase64String
, To/FromHexString
, ToString(X value, int toBase)
, ToX(string? value, int fromBase)
)
Avoid: int.Parse — you have to use a try
/catch
statement to handle invalid input, which is a less clean solution.
Use int.TryParse https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0#System_Int32_TryParse_System_String_System_Int32__ Int32.TryParse Method (System)
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the operation succeeded.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.