Arrays not averaging out correctly using a loop





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















namespace Files_and_Arrays_II
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button3_Click(object sender, EventArgs e)
{
this.Close();
}

private void button1_Click(object sender, EventArgs e)
{
StreamReader inputFile;
int doctor = 0;
double total = 0, average_sys = 0;
string name, DocN;

string doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
int systolic = new int[5];
int diastolic = new int[5];

OpenFileDialog openFile = new OpenFileDialog();

if (openFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(openFile.FileName);
while (!inputFile.EndOfStream)
{
name = inputFile.ReadLine();
for (int i = 0; i < 5; i++)
{
systolic[i] = int.Parse(inputFile.ReadLine());
diastolic[i] = int.Parse(inputFile.ReadLine());
}

//Calculates average for systolic
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
average_sys = total / 5;

doctor = int.Parse(inputFile.ReadLine());
DocN = doctors[doctor];
listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);

}
}
}
}
}


This is the file it is getting it from



When running the program I get the following averages for systolic: 184.6 (correct), 312 (wrong).



I've tried resetting the array at the end of the loop but that solves nothing










share|improve this question




















  • 1





    the only code using the diastolic array is just used to populate it, there's nothing else referencing it.

    – user1666620
    Nov 16 '18 at 15:48













  • Wheres the code calculating the diastolic average and outputting that result? I'm not seeing it.

    – JNevill
    Nov 16 '18 at 15:50











  • Did you intend to keep the total from one line while reading the next line? My guess is that you've just forgotten total = 0 at the end of the inner loop.

    – Jon Skeet
    Nov 16 '18 at 15:50













  • Umm, you don't reset your total. FYI: You can easily find such errors -- like variables not having the value you believe/expect -- by using the debugger (Learn to debug using Visual Studio)

    – elgonzo
    Nov 16 '18 at 15:51













  • And it's odd that you are doing this average calculation INSIDE your while loop. Load your arrays inside, calculate your average outside after they are loaded.

    – JNevill
    Nov 16 '18 at 15:52


















0















namespace Files_and_Arrays_II
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button3_Click(object sender, EventArgs e)
{
this.Close();
}

private void button1_Click(object sender, EventArgs e)
{
StreamReader inputFile;
int doctor = 0;
double total = 0, average_sys = 0;
string name, DocN;

string doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
int systolic = new int[5];
int diastolic = new int[5];

OpenFileDialog openFile = new OpenFileDialog();

if (openFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(openFile.FileName);
while (!inputFile.EndOfStream)
{
name = inputFile.ReadLine();
for (int i = 0; i < 5; i++)
{
systolic[i] = int.Parse(inputFile.ReadLine());
diastolic[i] = int.Parse(inputFile.ReadLine());
}

//Calculates average for systolic
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
average_sys = total / 5;

doctor = int.Parse(inputFile.ReadLine());
DocN = doctors[doctor];
listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);

}
}
}
}
}


This is the file it is getting it from



When running the program I get the following averages for systolic: 184.6 (correct), 312 (wrong).



I've tried resetting the array at the end of the loop but that solves nothing










share|improve this question




















  • 1





    the only code using the diastolic array is just used to populate it, there's nothing else referencing it.

    – user1666620
    Nov 16 '18 at 15:48













  • Wheres the code calculating the diastolic average and outputting that result? I'm not seeing it.

    – JNevill
    Nov 16 '18 at 15:50











  • Did you intend to keep the total from one line while reading the next line? My guess is that you've just forgotten total = 0 at the end of the inner loop.

    – Jon Skeet
    Nov 16 '18 at 15:50













  • Umm, you don't reset your total. FYI: You can easily find such errors -- like variables not having the value you believe/expect -- by using the debugger (Learn to debug using Visual Studio)

    – elgonzo
    Nov 16 '18 at 15:51













  • And it's odd that you are doing this average calculation INSIDE your while loop. Load your arrays inside, calculate your average outside after they are loaded.

    – JNevill
    Nov 16 '18 at 15:52














0












0








0








namespace Files_and_Arrays_II
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button3_Click(object sender, EventArgs e)
{
this.Close();
}

private void button1_Click(object sender, EventArgs e)
{
StreamReader inputFile;
int doctor = 0;
double total = 0, average_sys = 0;
string name, DocN;

string doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
int systolic = new int[5];
int diastolic = new int[5];

OpenFileDialog openFile = new OpenFileDialog();

if (openFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(openFile.FileName);
while (!inputFile.EndOfStream)
{
name = inputFile.ReadLine();
for (int i = 0; i < 5; i++)
{
systolic[i] = int.Parse(inputFile.ReadLine());
diastolic[i] = int.Parse(inputFile.ReadLine());
}

//Calculates average for systolic
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
average_sys = total / 5;

doctor = int.Parse(inputFile.ReadLine());
DocN = doctors[doctor];
listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);

}
}
}
}
}


This is the file it is getting it from



When running the program I get the following averages for systolic: 184.6 (correct), 312 (wrong).



I've tried resetting the array at the end of the loop but that solves nothing










share|improve this question
















namespace Files_and_Arrays_II
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button3_Click(object sender, EventArgs e)
{
this.Close();
}

private void button1_Click(object sender, EventArgs e)
{
StreamReader inputFile;
int doctor = 0;
double total = 0, average_sys = 0;
string name, DocN;

string doctors = new string[3] { "D. ABRAMS, MD", "D. JARVIC, MD", "T. PANOS, MD" };
int systolic = new int[5];
int diastolic = new int[5];

OpenFileDialog openFile = new OpenFileDialog();

if (openFile.ShowDialog() == DialogResult.OK)
{
inputFile = File.OpenText(openFile.FileName);
while (!inputFile.EndOfStream)
{
name = inputFile.ReadLine();
for (int i = 0; i < 5; i++)
{
systolic[i] = int.Parse(inputFile.ReadLine());
diastolic[i] = int.Parse(inputFile.ReadLine());
}

//Calculates average for systolic
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
average_sys = total / 5;

doctor = int.Parse(inputFile.ReadLine());
DocN = doctors[doctor];
listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);

}
}
}
}
}


This is the file it is getting it from



When running the program I get the following averages for systolic: 184.6 (correct), 312 (wrong).



I've tried resetting the array at the end of the loop but that solves nothing







c# arrays loops while-loop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 15:46









Daniel Mann

40.1k76390




40.1k76390










asked Nov 16 '18 at 15:43









nickelnickel

31




31








  • 1





    the only code using the diastolic array is just used to populate it, there's nothing else referencing it.

    – user1666620
    Nov 16 '18 at 15:48













  • Wheres the code calculating the diastolic average and outputting that result? I'm not seeing it.

    – JNevill
    Nov 16 '18 at 15:50











  • Did you intend to keep the total from one line while reading the next line? My guess is that you've just forgotten total = 0 at the end of the inner loop.

    – Jon Skeet
    Nov 16 '18 at 15:50













  • Umm, you don't reset your total. FYI: You can easily find such errors -- like variables not having the value you believe/expect -- by using the debugger (Learn to debug using Visual Studio)

    – elgonzo
    Nov 16 '18 at 15:51













  • And it's odd that you are doing this average calculation INSIDE your while loop. Load your arrays inside, calculate your average outside after they are loaded.

    – JNevill
    Nov 16 '18 at 15:52














  • 1





    the only code using the diastolic array is just used to populate it, there's nothing else referencing it.

    – user1666620
    Nov 16 '18 at 15:48













  • Wheres the code calculating the diastolic average and outputting that result? I'm not seeing it.

    – JNevill
    Nov 16 '18 at 15:50











  • Did you intend to keep the total from one line while reading the next line? My guess is that you've just forgotten total = 0 at the end of the inner loop.

    – Jon Skeet
    Nov 16 '18 at 15:50













  • Umm, you don't reset your total. FYI: You can easily find such errors -- like variables not having the value you believe/expect -- by using the debugger (Learn to debug using Visual Studio)

    – elgonzo
    Nov 16 '18 at 15:51













  • And it's odd that you are doing this average calculation INSIDE your while loop. Load your arrays inside, calculate your average outside after they are loaded.

    – JNevill
    Nov 16 '18 at 15:52








1




1





the only code using the diastolic array is just used to populate it, there's nothing else referencing it.

– user1666620
Nov 16 '18 at 15:48







the only code using the diastolic array is just used to populate it, there's nothing else referencing it.

– user1666620
Nov 16 '18 at 15:48















Wheres the code calculating the diastolic average and outputting that result? I'm not seeing it.

– JNevill
Nov 16 '18 at 15:50





Wheres the code calculating the diastolic average and outputting that result? I'm not seeing it.

– JNevill
Nov 16 '18 at 15:50













Did you intend to keep the total from one line while reading the next line? My guess is that you've just forgotten total = 0 at the end of the inner loop.

– Jon Skeet
Nov 16 '18 at 15:50







Did you intend to keep the total from one line while reading the next line? My guess is that you've just forgotten total = 0 at the end of the inner loop.

– Jon Skeet
Nov 16 '18 at 15:50















Umm, you don't reset your total. FYI: You can easily find such errors -- like variables not having the value you believe/expect -- by using the debugger (Learn to debug using Visual Studio)

– elgonzo
Nov 16 '18 at 15:51







Umm, you don't reset your total. FYI: You can easily find such errors -- like variables not having the value you believe/expect -- by using the debugger (Learn to debug using Visual Studio)

– elgonzo
Nov 16 '18 at 15:51















And it's odd that you are doing this average calculation INSIDE your while loop. Load your arrays inside, calculate your average outside after they are loaded.

– JNevill
Nov 16 '18 at 15:52





And it's odd that you are doing this average calculation INSIDE your while loop. Load your arrays inside, calculate your average outside after they are loaded.

– JNevill
Nov 16 '18 at 15:52












2 Answers
2






active

oldest

votes


















2














Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.



Like this:



                string name = inputFile.ReadLine();

//Calculates average for systolic
double total = 0;
for (int count = 0; count < systolic.Length; count++)
{
total += systolic[count];
}
double average_sys = total / 5;

int doctor = int.Parse(inputFile.ReadLine());
string DocN = doctors[doctor];
listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);


Even better, use var instead of setting the variable type in two places and risking getting it wrong.






share|improve this answer



















  • 1





    Yep. And declaring everything at the top is a symptom of coding styles (and instructors) that evolved in the days when many languages required this, and have not evolved towards better practice. I've seen declaring variables at the top taught in schools as "better style". It was true once; it's not today. Welcome to programming, where everything you think you know is really just a snapshot of how things were at one point in time.

    – Joel Coehoorn
    Nov 16 '18 at 16:31



















1














You're not resetting your variables for total and average for the second set of measurements.






share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341114%2farrays-not-averaging-out-correctly-using-a-loop%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.



    Like this:



                    string name = inputFile.ReadLine();

    //Calculates average for systolic
    double total = 0;
    for (int count = 0; count < systolic.Length; count++)
    {
    total += systolic[count];
    }
    double average_sys = total / 5;

    int doctor = int.Parse(inputFile.ReadLine());
    string DocN = doctors[doctor];
    listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);


    Even better, use var instead of setting the variable type in two places and risking getting it wrong.






    share|improve this answer



















    • 1





      Yep. And declaring everything at the top is a symptom of coding styles (and instructors) that evolved in the days when many languages required this, and have not evolved towards better practice. I've seen declaring variables at the top taught in schools as "better style". It was true once; it's not today. Welcome to programming, where everything you think you know is really just a snapshot of how things were at one point in time.

      – Joel Coehoorn
      Nov 16 '18 at 16:31
















    2














    Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.



    Like this:



                    string name = inputFile.ReadLine();

    //Calculates average for systolic
    double total = 0;
    for (int count = 0; count < systolic.Length; count++)
    {
    total += systolic[count];
    }
    double average_sys = total / 5;

    int doctor = int.Parse(inputFile.ReadLine());
    string DocN = doctors[doctor];
    listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);


    Even better, use var instead of setting the variable type in two places and risking getting it wrong.






    share|improve this answer



















    • 1





      Yep. And declaring everything at the top is a symptom of coding styles (and instructors) that evolved in the days when many languages required this, and have not evolved towards better practice. I've seen declaring variables at the top taught in schools as "better style". It was true once; it's not today. Welcome to programming, where everything you think you know is really just a snapshot of how things were at one point in time.

      – Joel Coehoorn
      Nov 16 '18 at 16:31














    2












    2








    2







    Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.



    Like this:



                    string name = inputFile.ReadLine();

    //Calculates average for systolic
    double total = 0;
    for (int count = 0; count < systolic.Length; count++)
    {
    total += systolic[count];
    }
    double average_sys = total / 5;

    int doctor = int.Parse(inputFile.ReadLine());
    string DocN = doctors[doctor];
    listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);


    Even better, use var instead of setting the variable type in two places and risking getting it wrong.






    share|improve this answer













    Others have pointed out the problem in this case, but it's a symptom of declaring variables at the top of the function. If you'd declared them close to where they are used, it would be obvious which variables apply to the whole function and which have a scope that only applies inside the loop.



    Like this:



                    string name = inputFile.ReadLine();

    //Calculates average for systolic
    double total = 0;
    for (int count = 0; count < systolic.Length; count++)
    {
    total += systolic[count];
    }
    double average_sys = total / 5;

    int doctor = int.Parse(inputFile.ReadLine());
    string DocN = doctors[doctor];
    listBox1.Items.Add(name + "t" + average_sys + "t" + DocN);


    Even better, use var instead of setting the variable type in two places and risking getting it wrong.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 16 '18 at 16:03









    Robin BennettRobin Bennett

    1,880413




    1,880413








    • 1





      Yep. And declaring everything at the top is a symptom of coding styles (and instructors) that evolved in the days when many languages required this, and have not evolved towards better practice. I've seen declaring variables at the top taught in schools as "better style". It was true once; it's not today. Welcome to programming, where everything you think you know is really just a snapshot of how things were at one point in time.

      – Joel Coehoorn
      Nov 16 '18 at 16:31














    • 1





      Yep. And declaring everything at the top is a symptom of coding styles (and instructors) that evolved in the days when many languages required this, and have not evolved towards better practice. I've seen declaring variables at the top taught in schools as "better style". It was true once; it's not today. Welcome to programming, where everything you think you know is really just a snapshot of how things were at one point in time.

      – Joel Coehoorn
      Nov 16 '18 at 16:31








    1




    1





    Yep. And declaring everything at the top is a symptom of coding styles (and instructors) that evolved in the days when many languages required this, and have not evolved towards better practice. I've seen declaring variables at the top taught in schools as "better style". It was true once; it's not today. Welcome to programming, where everything you think you know is really just a snapshot of how things were at one point in time.

    – Joel Coehoorn
    Nov 16 '18 at 16:31





    Yep. And declaring everything at the top is a symptom of coding styles (and instructors) that evolved in the days when many languages required this, and have not evolved towards better practice. I've seen declaring variables at the top taught in schools as "better style". It was true once; it's not today. Welcome to programming, where everything you think you know is really just a snapshot of how things were at one point in time.

    – Joel Coehoorn
    Nov 16 '18 at 16:31













    1














    You're not resetting your variables for total and average for the second set of measurements.






    share|improve this answer




























      1














      You're not resetting your variables for total and average for the second set of measurements.






      share|improve this answer


























        1












        1








        1







        You're not resetting your variables for total and average for the second set of measurements.






        share|improve this answer













        You're not resetting your variables for total and average for the second set of measurements.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 16 '18 at 15:50









        Schwarzie2478Schwarzie2478

        1,5581723




        1,5581723






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53341114%2farrays-not-averaging-out-correctly-using-a-loop%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            List item for chat from Array inside array React Native

            Thiostrepton

            Caerphilly