Hi everyone!
I'm writing a program to perform statistical calculations on some electrical equipment. In my entire program, this one part is messing with me so I broke it up into one separate just to debug.
Anyway, what the code below does is; define an array of 10 elements and each element is entered by the user. After each entry is entered the loop traverses and adds up the entered values to date printing out the sum to date. However at the end of the loop (ie: after entering the last value) the sum printed out is wrong.
I have a feeling it's got something to do with the vars being floats and ints.
PS: The code works fine if I declare "Resistor_Sum, Resistor[ArraySize]" as global vars but apparently this is bad practice and want to avoid this.
Code:
#include <stdio.h> // Needed for printf and scanf
#include <stdlib.h> // Needed for system()
#define ArraySize 9 // Define a constant array size
int main() {
// Define Variables
// Number of elements in the array (this should be 10 after counting)
int count = 0;
// Main resistor array variable which user enters, sum of resistors entered
float Resistor_Sum, Resistor[ArraySize];
for (int i = 0 ; i <= ArraySize ; i++) {
printf ("Enter resistor %d in [Ohms]: ", i);
scanf ("%f", &Resistor[i]);
count++;
Resistor_Sum += Resistor[i];
printf ("The sum is: %f, The count is: %d\n\n", Resistor_Sum, count);
}
system ("pause");
return 0;
}
Also below is a sample output:
Code:
Enter resistor 0 in [Ohms]: 10
The sum is: 10.000000, The count is: 1
Enter resistor 1 in [Ohms]: 20
The sum is: 30.000000, The count is: 2
Enter resistor 2 in [Ohms]: 30
The sum is: 60.000000, The count is: 3
Enter resistor 3 in [Ohms]: 40
The sum is: 100.000000, The count is: 4
Enter resistor 4 in [Ohms]: 50
The sum is: 150.000000, The count is: 5
Enter resistor 5 in [Ohms]: 60
The sum is: 210.000000, The count is: 6
Enter resistor 6 in [Ohms]: 70
The sum is: 280.000000, The count is: 7
Enter resistor 7 in [Ohms]: 80
The sum is: 360.000000, The count is: 8
Enter resistor 8 in [Ohms]: 90
The sum is: 450.000000, The count is: 9
Enter resistor 9 in [Ohms]: 100
The sum is: 200.000000, The count is: 10
Press any key to continue . . .
Thank you for your help!