2016-07-01 88 views
1
#include <iostream> 
using namespace std; 


int arr[100] = {}; 
int terms; 
int maxterms; 
int sum = 0; 

int main() { 
    cout << "How many terms would you like to add?" << endl; 

    cin >> terms; 

    terms = maxterms; 

    for (int x = terms; x >= 0; x--) { 
     cout << "Number " << (((maxterms)-x) + 1) << ": "; 
     cin >> arr[(maxterms - x)]; 
     cout << endl; 
    } 

    for (int x = 0; x < maxterms; x++) { 
     sum += arr[x]; 
    } 

    cout << "Your sum is: " << sum; 

    return 0; 
} 

这个简单的程序始终打印总和为零,并且只提示用户输入一次。如何改进这段代码,使其写入数组的连续索引,然后返回它们的总和?写入及阅读从使用for循环数组和用户输入

+0

@SilentMonk我没有看到这些是全局变量,所以这不是UB当然,你的答案是正确的。 – Holt

+0

@霍尔特,谢谢你的澄清。 – SilentMonk

回答

1

maxterms被初始化为0,因为它是一个全局变量。你是等式terms = maxterms你在哪里覆盖用户的输入为0.

所以for (int x = 0; x < maxterms; x++)根本不运行。因此sum总是0。对于提示用户输入次数的循环也是如此。

此外,您提示用户输入的循环运行的时间为terms+1次。

0

由于@SilentMonk指出,x = maxterms,所以循环退出。

您可以重新设计的循环,像这样:

for (int x = maxterms; x >= 0; x--) 
{ 
    sum += arr[x]; 
} 

这里x开始与它的价值等于maxterms,并下降,直到它的值是0,和arr[x]值加到sum每次迭代。

+0

我希望我能检查两个人作为正确的答案,因为你的延续也是非常有用的。 – jmantela

+0

谢谢您的确认。让我们希望代码编译没有错误。 –

-1

我只是检查你的代码,我看这行发现了这一点,

条款=最大项;

这将覆盖用户的输入与一些随机值,因为你不是初始化maxterms。

我想你想复制用户输入最大项所以这样做:

最大项=条款;

改变这一点,并尝试。