I tried to create a program which would give me an average score of 5 tests. First I created 5 variables that would be declared by an user. But I have a problem that I could not fix by myself. The output of my code shows a false average score of tests, probably I have a mistake somewhere and I would like you to help me in finding it.
Here is a full code:
using System;
namespace Test
{
class MathTest
{
static void Main()
{
string a, b, c, d, e;
Console.WriteLine("1st Test Score: ");
a = Console.ReadLine();
Console.WriteLine("2nd Test Score: ");
b = Console.ReadLine();
Console.WriteLine("3rd Test Score: ");
c = Console.ReadLine();
Console.WriteLine("4th Test Score: ");
d = Console.ReadLine();
Console.WriteLine("5th Test Score: ");
e = Console.ReadLine();
Console.WriteLine("Your Average Test Score is: {0}",
Convert.ToInt32(a + b + c + d + e) / 5);
}
}
}
Hopefully there is only one mistake in the last sentence, the formula. Thanks for your attention.
As others have correctly said, you need to convert the strings to numbers first, then add them, and then divide them.
That fixes some of your problems. However, not all your problems are over yet.
Next: what if someone types in a score of 75.5 ? Teachers sometimes give half points. Integer is not the correct data type. In C#, use decimal for quantities that are exact decimal quantities, and double for quantities that are physical amounts, like length or mass. You should convert all the strings to decimal, not int.
Next: what if someone types in "Hello" or nothing at all, instead of a number? Your program will crash. You need to use a method such as TryParse that detects this situation, and then you need to prompt the user accordingly to re-enter the number correctly.
Now, you should not be rewriting all that code five times over. Make a method which prompts the user in a loop to enter a number, and returns that number when they do so successfully. Always be breaking your problem down into smaller problems and then write a method which solves that problem. That way your main routine stays simple even when your program logic gets complicated.
Finally and most important: today is a good day to learn how to use a debugger. Learn how to find problems like this on your own, rather than asking strangers on the internet to do your work for you. Most of computer programming is debugging, so learn that skill now.
You should Convert.ToInt32 each item (a..e):
...
Console.WriteLine("Your Average Test Score is: {0}",
(Convert.ToInt32(a) +
Convert.ToInt32(b) +
Convert.ToInt32(c) +
Convert.ToInt32(d) +
Convert.ToInt32(e)) / 5.0);
Another (possible) problem is integer division: if you want to have floating point result (e.g. average score 3.5) you should divide by 5.0, not 5
You're concatenating strings first, then casting the result to Int and dividing by 5.
Cast every number first, before doing maths on them.
You are converting the concatenated string. Suppose the user enters:
1
2
3
4
5
Then (a+b+c+d+e) is "12345" and you are calculating 12345/5. You need to cast all strings separately first.
You have to convert before you Sum up.
Console.WriteLine("Your Average Test Score is: {0}", (Convert.ToInt32(a) + Convert.ToInt32(b) + Convert.ToInt32(c) + Convert.ToInt32(d) + Convert.ToInt32(e)/5)
Well, I found out my mistake in the comments and answers and fixed the code (Changed only a mid part)
int a, b, c, d, e;
Console.WriteLine("1st Test Score: ");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("2nd Test Score: ");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("3rd Test Score: ");
c = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("4th Test Score: ");
d = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("5th Test Score: ");
e = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your Average Test Score is: {0}", Convert.ToInt32(a + b + c + d + e) / 5.0);
Related
I have been working on a crypto currency market simulation console app. I have a block of code that's supposed to ask the user to enter how much of a coin they want to buy and then repeat (after user input) as long as the "maxcoins" variable has a value greater than 0. Just running this causes an infinite loop which doesn't allow the user time to input anything. I have tried using Console.ReadKey() to break the loop which works but still doesn't allow the user to type anything as the loop repeats as soon as they type a character. I've tried google but this is too specific of a question for me to find any helpful answers. Please go easy on me I'm still pretty new to programming!
My code starts here but the top few lines won't go into the code box for some reason.
int input = 0;
string inputst;
int maxcoins = 100;
while (maxcoins > 0)
{
//Tried Console.ReadKey(); here.
Console.WriteLine("Type a key number to show what you want to buy");
Console.WriteLine("Key Numbers: Monke Coin 1 | Buy None 00 |");
Console.WriteLine("You can buy " + maxcoins + " more coins this turn");
if (input == 1)
{
Console.WriteLine("How Much Monke Coin Do you want to buy? Enter number 0-" + maxcoins);
inputst = Console.ReadLine();
input = Convert.ToInt32(inputst);
maxcoins = (maxcoins - input);
Console.WriteLine("" + maxcoins);
}
}
Your input variable is never equal to 1, because you do not read it in the beginning of the loop.
Add the following line:
Console.WriteLine("You can buy " + maxcoins + " more coins this turn");
input = Convert.ToInt32(Console.ReadLine());
and it will do what you need.
The program is supposed to calculate compound interest by getting several inputs from the user and then applying those with the compound interest formula, however while gramatically correct, the program does everything correctly except for ouputting the calculated value. Any ideas why this might be happening?
using System;
namespace compoundCalc
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter investment sum:");
int investment = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter annual interest rate:");
double interestRate = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter the number of times per year that interest is compounded per period:");
int compoundNumber = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the number of periods the money is invested for:");
int investmentPeriod = Convert.ToInt32(Console.ReadLine());
double nt = Math.Pow((compoundNumber * investmentPeriod),(1+interestRate / compoundNumber ));
double futureCapital = investment * nt;
Console.WriteLine("The future value of your investment is:", Convert.ToString(futureCapital));
}
}
}
Console.WriteLine(String, Object) method signature requires the string include a format character, which you don't have.
If you want to use String interpolation, then that would look like
Console.WriteLine($"The future value of your investment is: {futureCapital}");
You need to tell the Console where to display the futureCapital add this {0} to last of your string
Console.WriteLine("The future value of your investment is: {0}",Convert.ToString(futureCapital));
or you can use string concatenation +
Console.WriteLine("The future value of your investment is: " + futureCapital);
or more convenient use string interpolation $
Console.WriteLine($"The future value of your investment is:{futureCapital}");
<RepairOrderEvent>
<EventType>Advisor - Shared Guidelines</EventType>
<EventDateTime>2019-01-07T11:18:38.8756279-06:00</EventDateTime>
<EventNotes>FAF: Refinish Time without Haz Waste or EPC Charge; Score: 11; Variance: 0.0; UniqueSequenceNum: 0; Insurance Score: 40</EventNotes>
</RepairOrderEvent>
<RepairOrderEvent>
<EventType>Advisor - Shared Guidelines</EventType>
<EventDateTime>2019-01-07T11:18:38.8756279-06:00</EventDateTime>
<EventNotes>FAF(Best Practice): Must Enter If Vehicle is Drivable; Score: 11; Variance: 0.0; UniqueSequenceNum: 0</EventNotes>
</RepairOrderEvent>
<RepairOrderEvent>
<EventType>Advisor - Shared Guidelines</EventType>
<EventDateTime>2019-01-07T11:18:38.8756279-06:00</EventDateTime>
<EventNotes>FAF(Best Practice): Bumper Overlap Prompt Answered Yes, No Estimate Line Note; Score: 11; Variance: 0.0; UniqueSequenceNum: 2; Insurance Score: 25</EventNotes>
</RepairOrderEvent>
<RepairOrderEvent>
<EventType>Advisor - Shared Guidelines</EventType>
<EventDateTime>2019-01-07T11:18:38.8756279-06:00</EventDateTime>
<EventNotes>FAF(Document): Insufficient Photos Provided: Include Damage Area; Score: 11; Variance: 0.0; UniqueSequenceNum: 0; Insurance Score: 10000</EventNotes>
</RepairOrderEvent>
I have the following XML Data. I am trying to find the aggregate of "score" and not "score" + "Insurance Score". I was thinking of using Xpath to find the first occurrence of score on each line and drop the remainder of the string. The end goal here is to be able to read each line for the first occurrence, drop the remainder of the string and find the sum of the score.
Any suggestions or help is welcomed and appreciated. Thank You!
Once you're at the point where you're processing the values of the EventNotes you could do something like this assuming every EventNotes has some kind of "Score".
var num = eventNotes
.Select(note => note
.Split(";")
.Where(part => part.Contains("Score"))
.Select(score => int.Parse(score.Split(' ')[1]))
.First())
.Aggregate((sum, val) => sum + val);
Which would give you the sum of all the first occurrences of a score in all EventNotes.
This is assuming you already have the XML parsing part though.
This question already has answers here:
Math.Round with negative parameter
(3 answers)
Closed 5 years ago.
I have a homework where im supposed to create a code which should let the user type in a decimal number and then ask how many decimals the user want the number to be rounded to. The homework assignment were given to us with minimal instruction on how to do it so we were supposed to look online. We were given a hint about Math.Round() and this is my code right now:
Console.WriteLine("Hej! Skriv in ett tal med decimaler.");
string strTal = Console.ReadLine();
double tal = Convert.ToDouble(strTal);
Console.WriteLine("Tack! Skriv nu in hur många decimaler du
vill ha med på ditt tal.");
string strAvrundaren = Console.ReadLine();
int avrundaren = Convert.ToInt32(strAvrundaren);
Console.WriteLine("Ditt tal är: " +
Math.Round(tal,avrundaren));
With this code I got it to work so that whenever the user writes a decimal number and then writes the x amount of decimals it should be rounded to it does so correctly. My problem is that I had the thought if someone were to input a negative decimal number (ex: -1, -2, -2,12313 etc..)? I tried and my code crashed when I did it. Now im coming to you guys for an explanation to why it does this.
EDIT: by saying it "crashes", whenever I write in a negative number in the terminal the window pops down to my sidebar and when I bring it back up nothing has happened on the terminal and I can write as much as I want in the terminal but nothing happens. Im on Visual Studio for the Mac if that helps.
Best Regards
Kian
Your program lacks input validation. Not only will a negative number cause it to crash, but any string that is not numeric will also cause an unhandled exception.
Typically a program should validate its inputs before attempting to use them. If the value isn't valid, you can ask the user to input it again. Example:
using System;
public class Program
{
public static void Main()
{
double tal;
while (true)
{
Console.WriteLine("Hej! Skriv in ett tal med decimaler.");
string strTal = Console.ReadLine();
var ok = double.TryParse(strTal, out tal);
if (ok) break;
}
int avrundaren;
while (true)
{
Console.WriteLine("Tack! Skriv nu in hur många decimaler du vill ha med på ditt tal.");
string strAvrundaren = Console.ReadLine();
var ok = int.TryParse(strAvrundaren, out avrundaren);
if (!ok) continue;
if (avrundaren < 0) continue;
break;
}
Console.WriteLine("Ditt tal är: " + Math.Round(tal,avrundaren));
}
}
Try it on DotNetFiddle
Rounding for negative numbers work: Here is a quick test:
var ans = Math.Round(-100.11119, 2);
Console.WriteLine(ans);
Please see fiddle as proof for above test.
If you pass a negative number for the 2nd argument like this:
var ans = Math.Round(-100.11119, -2);
Console.WriteLine(ans);
You will get a runtime error.
Run-time exception (line 7): Rounding digits must be between 0 and 15, inclusive.
Please see fiddle for above test.
Therefore, you need to check the number provided to you by the user and make sure it is between 0 and 15 (inclusive).
I have checked a bunch of places with very minimal help to help me figure out a methods way in visual studios to open up the console when running the code to prompt the user from the Console.Writeline("Please enter seconds to convert: "); to input the number of seconds that they are trying to convert, once thats put in it would then print the results of the conversion as "Your result is 00:00:00" . Im still in the process of learning more about c# so i have one slightly basic understanding so far and a basic solution but what i currently have is not that I'm trying to have for this project. My solution so far is :
class Program
{
static void Main(string[] args)
{
TimeSpan t = TimeSpan.FromSeconds(36100556);
Console.WriteLine(t.Days);
Console.WriteLine(t.Hours);
Console.WriteLine(t.Minutes);
Console.WriteLine(t.Seconds);
Console.WriteLine(t.ToString());
}
}
I think you need to follow these steps:
1) Send the message requesting the time with the Console.WriteLine.
2) Use the command Console.ReadLine, this will make the console to wait until the user puts the time that need to convert.
3) Read the value and make the math.
4) Display the value using WriteLine.
5) After display the value, put another Consol.ReadLine in order to avoid the console to hide before the user reads the result.
Hope it helps
Console.WriteLine("Enter number of seconds:");
double sec = 0;
// Check if user input correct integer
while(!double.TryParse(Console.ReadLine(),out sec))
{
Console.WriteLine("Your data is invalid. Please input again:");
}
TimeSpan t = TimeSpan.FromSeconds(sec);
Console.WriteLine("Your result is " + t.ToString(#"hh\:mm\:ss"));
Console.ReadLine();
You can use var x = Console.ReadLine() to read input from the console. May have to do some conversions since it will read a string of characters. You can utilize something like Convert.ToDateTime(x) or something to convert to whatever data type you need.
Console.Write("Enter Number of Seconds: ");
string SecondsStr = Console.ReadLine();
Double Seconds = 0;
if(!Double.TryParse(SecondsStr, out Seconds))
{
Console.WriteLine("Invalid number entered");
}
else
{
TimeSpan Time = TimeSpan.FromSeconds(Seconds);
Console.WriteLine(string.Format("Days: {0}, Hours: {1}, Minutes: {2}, Seconds: {3}", Time.Days, Time.Hours, Time.Minutes, Time.Seconds));
}