【问题标题】:My solution for a sum-difference function isn't working我的求和差函数解决方案不起作用
【发布时间】:2021-01-06 09:54:54
【问题描述】:

我正在尝试编写一个循环函数,它返回给定正整数 nVal 的计算结果。

给定 nVal,函数计算 1 + 2 - 3 + 4 - 5 + ... + nVal。因此,例如如果 nVal = 4,则该函数返回 1 + 2 - 3 + 4 的结果。我提出的解决方案是没有正确循环 nVal,我不知道如何解决它。

我可以尝试任何修复方法吗?

这是我目前的代码(顺便说一句,我使用的是 C 语言):

#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;
}

【问题讨论】:

  • 考虑一下循环for (i = nVal; i &lt;= nVal; i++)...请学习如何使用 debugger 来解决(或至少找到)此类问题在这里发布问题所需时间的一小部分。
  • 调试器是做什么的?我对 C 编程还是很陌生
  • int getValue (nVal) {...}:永远不要写这样的代码。应该是int getValue (int nVal) {...}。编译器应该给出警告,例如warning: type of 'nVal' defaults to 'int'
  • 这个循环 for (i = nVal; i
  • 转到您最喜欢的搜索引擎并搜索debugger for &lt;your environment&gt;(当然,您可以将&lt;your environment&gt; 替换为您使用的实际环境,例如Visual Studio、Linux 控制台或类似环境)。如果您想永远不只是一个“初学者”,那么了解如何使用调试器至关重要。使用调试器,您可以在监视变量的同时逐语句逐句执行代码并查看它们的值如何变化。

标签: c for-loop sum conditional-statements difference


【解决方案1】:

由于数字是连续的,我去掉了if elseif语句,我使用变量k将'+'反转为'-',我的循环从2开始到nVal

你的循环

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

只运行 1 次

所以,你应该把它改成

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

和 (nResult=1) 因为在你的练习中,符号从第三个数字改变,而不是从第二个数字改变

这里:

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

如果我写为 1 输入,输出是 2,我删除这一行

我的代码:

#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;

}

【讨论】:

  • 所以你不一定需要条件语句来切换运算符?
  • @MartyMcfly :您可以使用条件语句,但您的代码会很长
  • 数字是连续的,所以只用一个变量来改变符号
  • 您所做的不仅仅是“使用变量 k 将 '+' 反转为 '-'”。你有什么else改变了?你为什么做那个改变?请花一些时间阅读或刷新how to write good answers
  • 好的,谢谢指出。
猜你喜欢
  • 2021-09-23
  • 1970-01-01
  • 2019-06-13
  • 2015-06-19
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多