从2中的2分,然后计算3中的3
Counting from 2 in 2 then 3 in 3
我有这个作为我的IT作业"一只猴子打开了n个储物柜。但是到3英寸3,如果他遇到一个封闭的储物柜,他会打开它。他这样做是n次。"这个问题想知道哪些储物柜仍然打开。
有一个n = 10的示例,结果为2,5,10。我做错了什么?
//NOTE : 1-OPEN, 0-Closed
int a[10],n,i,j,k=2;
cout<<"Cate colivii exista? ";cin>>n;
for(i=0; i<n; i++)
{
a[i]=1;
}
for(i=0; i<n; i=i+k)
{
if(a[i]==1)
a[i]=0;
else if(a[i]==0)
a[i]=1;
k++;
}
for(i=0; i<n; i++)
{
if(a[i]==1)
cout<<i<<" ";
}
//K should have been a number but i changed it.
return 0;
}
我对其进行了重写,并改进了某些东西,将C样式换成C 样式
#include<iostream>
#include<vector>
using std::cout; //not using namespace std since that one is too big
using std::endl;
using std::vector;
//declaring but not implementing here, want only to describe what it does here, not how
//at this place, you might want to write a comment that describes what the function does
void locker_monkey(const unsigned int amount_lockers);
//keeping the main function simple
int main() {
//initializing every variable if possible,
//also using unsigned int since it should never be negative
unsigned int amount_lockers = 0;
cout << "Cate colivii exista? ";
cin >> amount_lockers;
locker_monkey(amount_lockers);
return 0;
}
enum LockerStatus{ closed, open }; //using enum to make values descriptive
void locker_monkey(const unsigned int amount_lockers){
//use std::vector instead of array
//if created with two arguments, the first is the size of the vector,
//the second the default value
vector<LockerStatus> lockers_status(amount_lockers, open);
//here comes the important part regarding your question, two loops:
for(unsigned int k=2; k<amount_lockers; k++){ //outer one increases k
for(unsigned int i=0; i<amount_lockers; i+=k){ //inner one increases i
if(lockers_status[i] == open){ //more descriptive that a[i] == 1
lockers_status[i] = closed;
}else{
lockers_status[i] = open;
}
}
}
cout << "open lockers: ";
for(unsigned int i=0; i<amount_lockers; i++){
if(lockers_status[i]==open)
cout<<i<<" ";
}
cout << endl; //you forgot that part in your code - you want to finish your line
}
重要的部分是创建双回路,即
for(unsigned int k=2; k<amount_lockers; k++){
for(unsigned int i=0; i<amount_lockers; i+=k){
至少如果我正确理解问题。
,由于您是初学者,我认为改进代码不会有任何伤害。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何计算文件中的"columns"数?
- C++如何计算用户输入的数字中的偶数位数
- 如何计算Big-O表示法中的平均渐近运行时间
- C++ 中的特征向量计算
- 如何计算常量字符**中的总字符数?
- 模板参数列表中的 false 在模板初始化期间计算为什么?
- 如何使用 O(n) 中的 DP 计算预期匝数?
- 计算单词中的音节数,但考虑到单词中彼此相邻的任何元音都算作一个音节
- C++ 中的"if"语句不会从左到右计算条件
- 如何计算文件中的生物数量?
- 计算 O(1) 中的幂函数
- 计算二进制文件中的位数
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 使用标准库计算字符串中的十进制数
- 计算阶乘的 C++17 倍表达式中的错误
- 如何知道我的Nvidia卡在C/C++中的计算能力
- Maya API中的计算WorldMatrix
- 初始化中的计算顺序
- dll在多大程度上加快了循环等代码中的计算速度