快速查找整数的倍数
Finding multiples of integers quickly
我用C++编写了这段特殊的代码,试图找出整数3&5低于1000,方法是使用while循环,然后将其存储在整数数组中。我还想打印出这些倍数中的每一个。但每次我调试这个程序时,它都会无休止地打印出"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;
}
当数字包含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;
}
应该是
threeArray[i - 1] = multiples;
而不是
multiples = threeArray[i - 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++;
}
}
我猜这个
multiples = threeArray[i - 1];
应该是
threeArray[i - 1] = multiples;
请尝试再次调试它,并在执行此行时监视multiples
。
multiples = threeArray[i - 1];
您正在用数组的(空)内容覆盖本地int——您的赋值方式不对。
您永远不会修改数组中的值。应该是这样的:
while (i < three_limit)
{
int multiples = 3*i;
threeArray[i-1] = multiples;
cout << threeArray[i - 1] << endl;
i++;
}
相关文章:
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 查找多个向量之间的公共元素(无整数元素)
- 查找满足浮点不等式方程的最小整数
- 递归函数,用于查找 2 个整数之间的最大值
- 在大整数数组中查找子数组
- 查找整数数组中最接近的数字
- C++ 将二进制字符串转换为整数或比较 2 个字符串以查找差异数
- 移位运算符如何在查找两个整数中的不同位数?
- 查找多维数组中整数的出现次数(以C++为单位)
- 在非负整数的未排序数组中查找第 k 个最小元素
- 如何使用字符串流查找字符串中的整数总和?
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- C++ 在数组中查找整数
- 函数中查找整数部首的意外行为/错误
- 如何使用字符串::与整数查找?C
- 查找整数中的重复模式
- 如何查找具有一组整数的函数的'max absolute sum'
- 查找序列中最大和最小的 2 个整数
- 在C++中使用 for 循环从用户输入中查找最大和最小整数
- 按 3 整数查找值的有效方法