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