开发者

Adding the sum of numbers using a loop statement

开发者 https://www.devze.com 2022-12-24 05:03 出处:网络
I need serious help dividing the positive numbers and the negative numbers. I am to accumulate the total of the negative values and separately accumulate the total of the positive values. After the l

I need serious help dividing the positive numbers and the negative numbers.

I am to accumulate the total of the negative values and separately accumulate the total of the positive values. After the loop, you are then to display the sum of the negative values and the sum of the positive values.

The data is suppose to look like this:

-2.3 -1.9 -1.5 -1.1 -0.7 -0.3 0.1 0.5 0.9 1.3 1.7 2.1 2.5 2.9

Sum of negative values: -7.8 Sum of positive

values: 12

So far I have this:

int main () {

    int num, num2, num3, num4, num5, sum, count, sum1;
    int tempVariable = 0;
    int numCount = 100;
    int newlineCount = 0, newlineCount1 = 0;
    float numCount1 = -2.3;

    while (numCount <= 150)
    {
        cout << numCount << " ";

开发者_开发百科        numCount += 2;
        newlineCount ++; 
        if(newlineCount == 6)
        {
            cout<< " " << endl;
            newlineCount = 0;
        }
    }
    **cout << "" << endl;
    while (numCount1 <=2.9 ) 
    {
        cout << numCount1 << " ";
        numCount1 += 0.4;
        newlineCount1 ++;     
    } while (  newlineCount1  <= 0 && newlineCount >= -2.3 );

    cout << "The sum is " << newlineCount1 << endl;**

    return 0;   
}


I do not know C/C++ but here is a general idea of the loop assuming the values are coming from an array. (since I am unaware of how they are coming in, i.e. user input, etc.)

Logic:

  • Use a for loop structure opposed to a while, to loop over each element of the array.
  • Initialize two variables to keep count, positiveSum and negativeSum.
  • At each iteration of the element, check to see if it's greater than 0. That's how you can divide the positive and negative numbers accordingly.
  • If greater than zero, add the element onto the running positiveSum, else add it to the running sum of negativeSum.
  • When the loop finishes, positiveSum and negativeSum should have the calculated sum.

If this is homework, (I don't remember if the homework tag was there prior to the question, or was added on later) this pseudo code should point you in the right direction without explicitly doing the entire work for you.

Pseudo Java Code (not tested or compiled)

 // as a good convention, I always initialize variables, 
 // for numbers I always use zero's.
double positiveSum, negativeSum = 0.0; 
 // assuming array holds the array of values.
for (i=0; i < array.length; i++) {
 // if positive, add it to the count
 if (array[i] > 0) positiveSum = positiveSum + array[i];
 // else negative
 else negativeSum = negativeSum + array[i];
}

Once it's completed, both positiveSum and negativeSum should hold the correct calculated sum.

If you have any questions along the way, I can edit my answer to help you achieve the correct answer, I wish I could give it away but that's what your responsibilities are for homework.


I would loop through each number individually, let's call it currentValue

if the number is negative, negativeNumberTotal += currentValue

else if positive, positiveNumberTotal += currentValue

You will get your individual totals that way. Very simple.


You are clearly overcomplicating the problem. First of all you don't need two separate loops for the numbers, as there is a constant 0.4 difference between them, even between -0.3 and 0.1. You only have to check if it's negative or not to know how to sum them up.

Loops are simpler if you use an integer as counter. As you want 14 numbers you can simply count from 0 to 13, and from that you can easily calculate the corresponding floating point value.

Example C# code:

double negSum = 0.0, posSum = 0.0;
for (int i = 0; i < 14; i++) {
  double number = -2.3 + (double)i * 0.4;
  if (number < 0) {
    negSum += number;
  } else {
    posSum += number;
  }
}

You can of course use a floating point number in the loop, but then you need to take into account the inexact nature of floating point numbers. You should make sure to use an ending interval that is something like halfway between the last number that you want and the next.

double negSum = 0.0, posSum = 0.0;
for (double number = -2.3; number < 3.1; number += 0.4) {
  if (number < 0) {
    negSum += number;
  } else {
    posSum += number;
  }
}

Also, when repeatedly accumulating floating point numbers (like adding 0.4 over and over again), you also accumulate rounding errors. Most numbers can't be represented exactly as floating point numbers, so it's likely that you are actually adding something like 0.3999999999999994225 instead of 0.4 each iteration. It's not likely to add up to something that is enough to show up in this small example, but you should be aware of this effect so that you can anticipate it in situations with more numbers.


You have several magic numbers, whose purpose I'm not sure of, e.g numcount1 = -2.3 In general you want to avoid magic numbers.

You might want to give your variables more descriptive names than num1, num2, etc.

Could you explain more precisely what the parameters are for your assignment?

EDIT:

I've noticed that you are using very weird conditions to control your loop. You are continuing until numcount1 is = 2.9, which is a very fragile sort of setup. The first thing I would do in your shoes is to rewrite your program so that the loop terminates when there are no more numbers to add. (Alternatively, you could just make it stop after, say 12 values.)

EDIT AGAIN:

OK, how about this

int sumOfPos = 0, sumOfNeg = 0, currentValue = -2.3, terminationValue = 2.9;

while (currentValue <= terminationValue) {
    if (  /* there is a missing condition here */ ) {
                // need a statement here to increment your negative counter
    } else {
                // need a statement here to increment your positive counter
    }
}
        // put some statements here to do output


This is easily solvable with pure math:

lowerBound = -2.3
upperBound = 2.9
incAmount = 0.4
signChange = lowerBound % incAmount
numBelowChange = -(lowerBound-signChange)/incAmount
avgNegValue = -(numBelowChange+1)/2.0*incAmount + signChange
sumOfNegative = numBelowChange*avgNegValue
numAboveChange = (upperBound-signChange)/incAmount
avgPosValue = (numAboveChange+1)/2.0*incAmount + signChange
sumOfPositive = numAboveChange*avgPosValue + signChange

It's more accurate, and more efficient than looping and adding.

With the constants you provided,

signChange     =  0.1
numBelowChange =  6.0
avgNegValue    = -1.3
sumOfNegative  = -7.8
numAboveChange =  7.0
avgPosValue    =  1.7
sumOfPositive  =  12.0

If you're unfamiliar with the % operator, x%y means "divide x by y and return the remainder". So 5%2=1

http://en.wikipedia.org/wiki/Modulo_operator


I'm not a programmer, but I thought it was best to keep the inside of a loop as lean as possible. This version works without any if statements inside the loop, just simple addition. It's late at night, and I've had a couple of whiskies, but I think this algorithm would work (it worked when I tried implementing it in python). It's psuedo code, so you'll have to write it up in yr language of choice:

neg_total =0
abs_total=0

loop with i in all_your_numbers
    total += i
    abs_total += abs(i)
end

neg_total=(total-abs_total)/2
pos_total=abs_Total+neg_Total

print "sum of negative values =", neg_total
print "sum of positive values =", pos_total

I'm not sure if this is good programming practice, I'm just chuffed that it worked. Points if you can explain how.

0

精彩评论

暂无评论...
验证码 换一张
取 消