1

刚到这里的论坛并开始学习 C++。这个网站已经在语法和其他方面帮助了我很多。我试图用我的代码做的是将数字打印到屏幕上,有时间延迟,然后打印下一个数字。目前,时间延迟有效,但它会打印生成的所有 13 个数字。关于我做错了什么的任何想法?

这是我的代码:

#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <windows.h>
using namespace std;

int main( ) 
{

// Function prototypes
int random ( int minValue, int maxValue);

// Constant declarations
const int maxValue = 9;
const int minValue = 0;

// Local variable declarations
int seed;
int numberOfPeople;
int peopleCount = 0;
int numberCount;
int number;

 // Initialize the random number generator
 cout << "Welcome to the Lottery!" << endl;
 cout << "Enter your lucky number to start: " << endl;
 cin >> seed;
 srand (seed);   

 // Generate and display numbers
 cout << "Enter the number of people participating in the lottery:" << endl;
 cin >> numberOfPeople;

 cout << "Your lucky lottery numbers for the day are:" << endl;
 cout.setf (ios::left, ios::adjustfield);
 cout << setw(8) << "Pick 3" << setw(10) << "Pick 4" <<
   setw(15) << "Pick 6" << endl;

 while (peopleCount < numberOfPeople) {
   numberCount = 0;
      while (numberCount < 13){
         number =  random (minValue, maxValue);
         Sleep (500); // pauses for half a second
         cout << number << " ";

       if (numberCount == 2){
           cout << "  "; }
       else if (numberCount == 6){
           cout << "  ";       }
       else if (numberCount == 12){
           cout << endl;          } //end if, else if           

       numberCount++;     
     } //end nested while
  peopleCount++;
  } // end while

return 0;
} // end main()

/**
*  Produces a pseudo-random number
*  @param minValue    minimum value that can be generated
*  @param maxValue    maximum value that can be generated
*
*  @return         psuedo-random number in the specified range
*/

int random ( int minValue, // min possible number to be generated
        int maxValue)  // max possible number to be generated
{
return ( (rand() % maxValue) + minValue);
} // end random()
4

1 回答 1

0

cout 一般是缓冲的,换行符会导致缓冲区刷新到屏幕上。当您在同一行显示数字时,这可以解释尽管您已经构建了延迟,但所有内容都一次显示。

用于cout.flush();强制在没有缓冲延迟的情况下完成输出。您也可以使用操纵器形式cout << number << " " << flush;

于 2014-09-17T23:18:29.317 回答