Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to write a loop function that returns the result of a computation given a positive integer nVal.

Given nVal, the function computes for 1 + 2 - 3 + 4 - 5 + ... + nVal. So for example if nVal = 4, the function returns the result of 1 + 2 - 3 + 4. The solution I made isn't looping nVal properly and I don't know how to fix it.

Any fixes that I can try?

Here's my code so far (Btw I'm using C language):

#include <stdio.h>

int getValue (nVal)
{
  int i, nResult = 0;
    
  for (i = nVal; i <= nVal; i++) 
  {
    if (i % 2 == 0) 
    {
      nResult += i;
    } 
    else if (i % 2 == 1)
    {
      nResult -= i;
    }
  }
  if (nVal == 1)
    nResult +=i + 1;
      
  return nResult;
}
    
int main ()
{
  int nVal, nResult; 
    
  printf ("Enter n value: ");
  scanf ("%d", &nVal);
    
  nResult = getValue(nVal);
  printf ("Result: %d", nResult);
    
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
236 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because the numbers are consecutives,I removed the if elseif statement ,I use the variable k to reverse '+' to '-',my loop start from 2 to nVal

Your loop

for (i = nVal; i <= nVal; i++)

runs just 1 time

so ,you should changed it to

for (i = 2; i <= nVal; i++)

and (nResult=1)because in your exercise the sign changed from the third number, not from the second number

here:

if (nVal == 1)
nResult +=i + 1;

If I write as 1 input ,the output is 2 ,I remove this line

my code:

#include <stdio.h>

int getValue (nVal)
{
int i, nResult = 1;
int k=1;
for (i = 2; i <= nVal; i++)
{
     nResult+=i*k;
     k*=-1;
}
return nResult;

}

int main ()
{
int nVal, nResult;
printf ("Enter n value: ");
scanf ("%d", &nVal);

nResult = getValue (nVal);

printf ("Result: %d", nResult);

return 0;

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...