如何将for循环转换为while循环c ++

时间:2017-12-02 18:54:11

标签: c++

我正在尝试在c ++中将for循环转换为while循环并在随机数生成器中检查重复项以生成乐透数字到目前为止我正在尝试的所有东西似乎都让编译器非常不满意我真的可以使用一些指针。它是Harray()函数中的for循环,它为Balls []数组提供信息 我想转换为while循环。

#include<iostream>
#include<cstdlib>  // to call rand and srand.
#include<ctime>    // to make rand a bit more random with srand(time(0)) as     first call. 
#include<iomanip>  // to manipulate the output with leading 0 where neccesary.

using namespace std;

// Hrand() function create and return a random number.
int Hrand()
{
    int num = rand()%45+1;  // make and store a random number change 45 for more or less Balls.
    return num;             // return the random number.
}

// Harray() function create and fill an array with random numbers and some formatting.
void Harray()
{
    int Balls[6];  // change the number in Balls[6] and in the for loop for more or less nrs. a row. 
    for(int x=0; x<=6; x++)  //the loop to fill array with random numbers.
    {
        int a;           // made to pass the Balls[x] data into so i can format output.
        int m = Hrand(); // calling the Hrand() function and passing it's value in int m.
        Balls[x] = m;    // throwing it into the array tought i did this because of an error.
        a = Balls[x];    // throwing it into int a because of an type error.
        cout<<"["<<setfill('0')<<setw(02)<<a<<"]";  //format output with leading 0 if neccesary.


    }
    cout<<endl;      // start new row on new line.
}
// Main function do the thing if compiler swallows the junk.
int main()            // start the program.
{
    int h;            // int to store user cchoice.
    srand(time(0));   // make rand more random.

    cout<<"How many rows do you want to generate?"<<endl; // ask how many rows?
    cin>>h;                                       // store user input.
    for(int i=h; h>0; h--)   // produce rows from user input choice.
    {
        Harray();            // calling Harray function into action.
    }
    return 0;                // return zero keep the comipler happy.
}  

我想要连续六个不同的数字,但我不知道如何使用for循环到达那里我认为while循环是可行的方式,但我愿意接受任何可行的建议。我刚开始使用c ++,我可能忽略了一些选项。

3 个答案:

答案 0 :(得分:0)

int x=0;
while(x<6)
{
    int a;format output.
    int m = Hrand();value in int m.
    Balls[x] = m;   because of an error.
    a = Balls[x];   
    cout<<"["<<setfill('0')<<setw(02)<<a<<"]";
    x++;
}

在这里,我还修复了一个错误。由于Balls有6个元素,因此最后一个元素为5.因此,您需要x<6而不是x<=6。这也适用于for循环。

while循环的一个缺点是你不能用它们声明局部变量。

答案 1 :(得分:0)

首先,你应该意识到for循环和while循环之间的区别主要是语法 - 你可以用一个做什么,你也可以做另一个。< / p>

在这种情况下,根据你所说的你想要的输出,你可能真正想要的是这样的:

std::vector<int> numbers;
std::set<int> dupe_tracker;

while (dupe_tracker.size() < 6) {
    int i = Hrand();
    if (dupe_tracker.insert(i).second)
        numbers.push_back(i);
}

这里的基本想法是dupe_tracker保留您生成的每个数字的副本。因此,您生成一个数字,并将其插入到集合中。如果数字已经在集合中,那将失败(并在retval.second中返回false)。因此,我们只在结果向量中添加数字,如果它已经在集合中 not (即,如果它是唯一的)。

答案 2 :(得分:-1)

  

如何将for-loop转换为while-loop

#include <iostream>

class T545_t
{
   // private data attributes
   int j;

public:

   int exec()
      {
         // A for-loop has 3 parameters, authors often fill 2 of them with magic
         // numbers.  (magic numbers are usually discouraged, but are expected
         // in for-loops)

         // Here, I create names for these 3 for-loop parameters
         const int StartNum  = 2;
         const int EndNum    = 7;
         const int StrideNum = 2;

         std::cout << std::endl << "  ";
         for (int i = StartNum; i < EndNum; i += StrideNum ) {
            std::cout << i << "  " << std::flush;
         }
         std::cout << std::flush;


         // A while-loop must use / provide each of these 3 items also, but
         // because of the increased code-layout flexibility (compared to
         // for-loop), the use of magic numbers should be discouraged.

         std::cout << std::endl << "  ";
         j = StartNum;
         do {
            if (j >= EndNum) break;
            std::cout << j << "  " << std::flush;
            j += StrideNum;
         } while(true);
         std::cout << std::flush;


         std::cout << std::endl << "  ";
         j = StartNum;
         while(true) {
            if (j >= EndNum) break;
            std::cout << j << "  " << std::flush;
            j += StrideNum;
         }
         std::cout << std::flush;

         std::cout << std::endl << "  ";
         j = StartNum;
         while(j < EndNum) {
            std::cout << j << "  " << std::flush;
            j += StrideNum;
         }
         std::cout << std::endl;


         return 0;
      }
}; // class T545_t

int main(int , char** )
{
   T545_t   t545;
   return(t545.exec());
}

问我'j'在哪里宣布?

此代码标记为C ++,因此在本例中,我在此类定义的私有数据属性“section”中声明了“j”。那就是你要找的地方吧?

如果你的c ++代码没有类,那有什么意义呢?