从2中的2分,然后计算3中的3

Counting from 2 in 2 then 3 in 3

本文关键字:中的 计算 然后 2分      更新时间:2023-10-16

我有这个作为我的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){

至少如果我正确理解问题。

,由于您是初学者,我认为改进代码不会有任何伤害。