我用C ++写出了这个特殊的代码,试图找出整数3&的所有倍数。通过使用while循环然后将其存储在整数数组中,低于1000。我还想打印出这些倍数。但每次我调试这个程序时,它都会无休止地打印出'0'。我只是不明白。有人可以解释一下如何更正此代码以及为什么会出现异常输出?
#include <iostream>
using namespace std;
int main()
{
const int three_limit = 334;
const int five_limit = 200;
int threeArray[three_limit] = {0};
int fiveArray[five_limit] = {0};
int i = 1, j = 1;
while (i < three_limit)
{
int multiples = 3*i;
multiples = threeArray[i - 1];
cout << threeArray[i - 1] << endl;
i++;
}
while (j < five_limit)
{
int multiples = 5*i;
multiples = fiveArray[j - 1];
cout << fiveArray[j - 1] << endl;
j++;
}
char response;
cin >> response;
return 0;
}
答案 0 :(得分:2)
当数字包含3和5的倍数时,您的输出将有重复项,例如15,30。
有些建议使用乘法或mod(%)这些建议非常慢,但使用二进制数组的解决方案要快得多,这也有助于避免重复问题。类似的东西:
int main() {
bool nums[1001];
for(int i = 1; i < 1001; ++i)
nums[i] = 0;
for(int i = 3; i < 1001; i += 3)
nums[i] = 1;
for(int i = 5; i < 1001; i += 5)
nums[i] = 1;
for(int i = 1; i < 1001; ++i)
if(nums[i])
cout << i << endl;
}
答案 1 :(得分:1)
应该是
threeArray[i - 1] = multiples;
而不是
multiples = threeArray[i - 1];
答案 2 :(得分:1)
请参阅以下代码,以生成5的倍数
#include<stdio.h>
int main(){
int max=1000;
int i=1,result=0;
while(result!=max && i!=200)
{
result=5*i; // change the 5 by 3 for multiples of 3
printf("\n %d",result);
i++;
}
}
答案 3 :(得分:0)
我猜这个
multiples = threeArray[i - 1];
应该是
threeArray[i - 1] = multiples;
再次尝试调试,并在执行此行时观看multiples
。
答案 4 :(得分:0)
multiples = threeArray[i - 1];
您正在使用数组的(空)内容覆盖本地int - 您的分配方式错误。
答案 5 :(得分:0)
您永远不会修改数组中的值。它应该是这样的:
while (i < three_limit)
{
int multiples = 3*i;
threeArray[i-1] = multiples;
cout << threeArray[i - 1] << endl;
i++;
}