-1
if(passWord == passWordInput)
{
    for( int test =1; test <5; test++)
    {
        if(grade >= 90 && grade <=100)
        {   
        Console.WriteLine("Exam {0} is {1},A", test, grade);
         grade = num.Next(0,100);
         totalGrade += grade;
        }
        else if(grade <90 && grade >=80)
        {
         Console.WriteLine("Exam {0} is {1},B", test, grade);
         grade = num.Next(0,100);
          totalGrade += grade;
        }
        else if(grade >= 70 && grade < 80)
        {
         Console.WriteLine("Exam {0} is {1},C", test, grade);
         grade = num.Next(0,100);
          totalGrade += grade;
        }
    else if(grade >=60 && grade < 70)
    {
     Console.WriteLine("Exam {0} is {1},D", test, grade);
     grade = num.Next(0,100);
      totalGrade += grade;
    }
    else
    {
     Console.WriteLine("Exam {0} is {1},F", test, grade);
     grade = num.Next(0,100);
      totalGrade += grade;
    }
 }
 //declaring a new variable here to save on code lines 
       decimal average = totalGrade / 4m;
        Console.WriteLine("Average: {0}", average);
}

When the average prints out its always incorrect if off by a few numbers and I have no idea how to fix it or what I'm doing wrong. it always too low. I tried to declare the variable in the same part of code where my other variables are but it average always came out to 0. I also had the variable update after totalgrade update but still came out to be the same. The answer was always to low by a few numbers.

Flamaryu
  • 3
  • 1
  • no that part is ok, everything prints out like I need just the average dont – Flamaryu Jun 28 '20 at 14:27
  • do you realize that `grade` will be 0 the first iteration and that you will sum an extra grade in the last one? – Gusman Jun 28 '20 at 14:28
  • 1
    @TaW 85 is < 90 and >= 80... – Gusman Jun 28 '20 at 14:28
  • got it I will fix that part but the grade don't start at 0 I'm just doing Random num gen. for grad they all print out fine. i have totalgrade start at 0. – Flamaryu Jun 28 '20 at 14:36
  • Move the rendom generation of grade outside the ifs and directly after the for. Then your average will be correct – Steve Jun 28 '20 at 14:40
  • Did you step through the code in a debugger? Using a debugger and stepping through code and using that as an aid in logically reasoning about what your code is doing and why is a critical programming skill. – Daniel Mann Jun 28 '20 at 15:26

3 Answers3

1

Ok, lets "debug" your code to see what's happening.

We start at the for loop, test is 1 and grade has no value (I will assume you have initialized it to zero), so the code enters on the last if, sets an F to the exam, generates a new grade and adds it to the totalGrade. As you can see the logic is flawed since it's begining.

Let's go to the last iteration of the loop: test is 4 and grade is a random number (lets assume 100 for simplicity). The code enters the first if condition, prints the result AND, generates a new grade and adds it to totalGrade. See the problem?

You are using always 0 for the first iteration, and in the last one you add an extra value to grade.

The solution is very simple: generate the grade value at the begining of the loop and sum it to totalGrade:

for( int test =1; test <5; test++)
{
    grade = num.Next(0,100);
    totalGrade += grade;

    //Now you can check the grade value and print the result (without generating again grade, of course)
}
Gusman
  • 13,944
  • 2
  • 26
  • 43
0

I believe this is because you firstly print out a grade, then you randomize it and add it to the sum. So you have scenario like

-> Print out 0, randomize 35, add 35.

-> Print out 35, randomize 49, add 49.

In the end, what you print out is not what you add to your average, thus your average is off a bit. I refactored the whole code for you:

        var grade = 0;
        var totalGrade = 0;
        var num = new Random();

        if (password == passwordInput)
        {
            for (int test = 1; test < 5; test++)
            {
                grade = num.Next(0, 100);
                totalGrade += grade;

                if (grade >= 90 && grade <= 100)
                {
                    Console.WriteLine($"Exam {test} is {grade},A");
                }
                else if (grade >= 80 && grade < 90)
                {
                    Console.WriteLine($"Exam {test} is {grade},B");
                }
                else if (grade >= 70 && grade < 80)
                {
                    Console.WriteLine($"Exam {test} is {grade},C");
                }
                else if (grade >= 60 && grade < 70)
                {
                    Console.WriteLine($"Exam {test} is {grade},D");
                }
                else
                {
                    Console.WriteLine($"Exam {test} is {grade},F");
                }
            }

            var average = totalGrade / 4m;
            Console.WriteLine($"Average: {average}");
        }

Also, knowing that you're just starting I'll give you few tips:

  • Read about string interpolation for putting variables into the strings. It is a very cool feature in C# which I admire a lot.
  • Remember about proper spacing and tabs in code. It just helps with the readability. You can use some plugins or built in settings for formatting files on save, like this extension for Visual Studio or this option in Visual Studio Code.
  • var is a really cool keyword. I probably use it too much, but generally I like to follow this article.
  • Try your best to avoid code redundancy - in your example you do the same exact thing in every if/else statement (which is randomizing the grade and adding to the sum), when it could be simply placed somewhere at the beginning or at the end of the loop. Whenever you write duplicate code ask yourself a question - do I really need to have the same code in two different places or am I doing something wrong? 95% of the time you really don't need ti rewrite the same code, but make a small refactor. It improves readability a lot!

Have fun learning the language!

Hakej
  • 32
  • 5
-1
int totalGrade = 0;
var num = new Random();

(int score, string letter)[] gradeTable = 
        { (90, "A"), (80, "B"), (70, "C"), (60, "D"), (0, "F") };

for(int test = 1; test < 5; test++)
{
    int grade = num.Next(0,100); 
    var letter = gradeTable.First(test => grade>=test.score).letter;
    Console.WriteLine($"Exam {test} is {grade},{letter}");
    totalGrade += grade;
}
var avg = totalGrade / 4m;
Console.WriteLine($"Average: {avg}");

See it work:

https://dotnetfiddle.net/aMKs2O

Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
  • Output: `Exam 1 is 8,A Unhandled exception. System.InvalidOperationException: Sequence contains no matching element at System.Linq.ThrowHelper.ThrowNoMatchException() at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate) at Program.Main() Command terminated by signal 6` – Gusman Jun 28 '20 at 15:37
  • 1
    @Gusman somehow in copy/pasting from .net fiddle I ended up reversing the comparison. Oops. It's right now. – Joel Coehoorn Jun 28 '20 at 15:40