2015-01-17 2 views
-2

사용자가 프롬프트 번호 (1-4)를 입력해야하는 간단한 프로그램을 만들고 싶었습니다. 계속되는 조건은 사용자가 선택한 레벨로 정의 된 시간의 숫자를 입력하고 정확한 숫자를 입력하는 것을 기반으로합니다. 문제는 프로그램이 번호가 정확한지 인식하지만, 원하는만큼 오래 걸릴 수 있으며 게임을 멈추지 않습니다. 이 "15 분"프로그램은 C++에 대한 파고가 될 것으로 예상되었지만, 혼란스러운 시계 알고리즘과 혼동의 주말 프로젝트로 바뀌 었습니다. 아래는 전체 소스 코드입니다. Here 표준에서는 당신이 현재 상태의에서 프로그램을 테스트 할 수 있도록 온라인의 C++ 에뮬레이터에 연결 ...C++ 시계가 작동하지 않습니다.

#include <iostream> 
#include <time.h> 
#include <ctime> 
#include <unistd.h> 


using namespace std; 

int main() { 

    //input 
    string numberGuessed; 
    int intNumberGuessed; 
    int score = 0; 
    int actualNumber; 
    int gameOver = 0; 

    //Level Select Variables 
    char level = {0}; 
    string input = " "; 
    double timeForInput; 


    //initialize random seed 
    srand (time(NULL)); 


    //Generates random number 
    actualNumber = rand() % 4 + 1; 

    //LEVEL SELECTOUR 
    cout << "Select A Level: 'e' 'm', or 'h': "; 
     getline(cin, input); 

     if (input.length() == 1) { 
      level = input[0]; 
     } 

     if (level == 'e') { 
      cout << "You Have Selected Easy..." << endl; 
      cout<< "You Have .5 Second to Enter" << endl; 
      timeForInput = 5; 

     } else if(level == 'm'){ 
      cout << "You Have Selected Medium..." << endl; 
      cout<< "You Have .2 Seconds to Enter" << endl; 
      timeForInput = 2; 

     } else if(level == 'h'){ 
      cout << "You Have Selected HARD!!!" << endl; 
      cout<< "You ONLY Have .1 Seconds to Enter" << endl; 
      timeForInput = 1; 

     } else { 
      cout << "You LOSE! GOOD DAY SIR!" << endl; 
     } 

     //Instructions and Countdown 
     cout<<"Press The Number and Hit Enter in The Amount of Time Provided"<<endl; 
     sleep(1); 
     cout<<"3"<<endl; 
     sleep(1); 
     cout<<"2"<<endl; 
     sleep(1); 
     cout<<"1"<<endl; 
     sleep(1); 
     cout<<"GO!"<<endl; 
     cout<<"--------------------------------------------------------------------------------"<<endl; 
     cout<< "Enter the Numbers As They Appear:"<<endl; 
     cout<<endl; 
     cout<<endl; 
     cout<<endl; 
     sleep(1); 
     double duration = 0.0; 




     do { 
     //Procedere For Each Round 

     clock_t start; 
     clock_t finish; 


     start = clock(); 
     finish = clock(); 

     double delay = (double)(finish-start); 


     //Clock 
      start = clock(); 

      cout<<"The number is: "<< actualNumber<<endl; 
      getline(cin, numberGuessed); 
      intNumberGuessed = stoi(numberGuessed); 

      finish = clock(); 

      double elapsed = (double)(finish-start); 
      elapsed-=delay; 

      duration = elapsed/CLOCKS_PER_SEC; 
      cout<<duration<<endl; 

      //Test User's input 
      if((intNumberGuessed == actualNumber) && (duration <= (timeForInput/10))){ 
       score += 1; 
       gameOver = 0; 

      } else if ((intNumberGuessed != actualNumber) || (duration >= (timeForInput/10))) { 
       gameOver = 1; 
      } 

      //Reset Number 
      actualNumber = rand() % 4 + 1; 

     } while (gameOver != 1); 


     cout<<"You Failed!"<<endl; 
     sleep(1); 
     cout<<"Your Score Was: "<<score<<endl; 

     return 0; 

} 
+1

이'수 duration' 안를' (clock() - start)/CLOCKS_PER_SEC'? –

+0

방금 ​​시도했지만 문제가 해결되지 않았지만 코드가 전반적으로 개선되었습니다. 고마워, – Noguiguy

+0

당신은 입력 후 기간을 계산하려는 것 같습니다. 현재 구조가 두 가지 시계 호출이 연속적으로 구성되어 있습니다. –

답변

2

입니다 clock()은 다음과 같습니다 어떤 도움을

편집이 ... 좋은 것 프로세스가 사용하는 대략적인 프로세서 시간을 반환하도록 지정되었습니다. 특히 이것은 표현식 (finish-start)의 결과가 경과 된 월 클럭 시간과 같지 않다는 것을 의미합니다. 예를 들어 1 초 동안 CPU를 씹는 4 개의 스레드를 측정하면 약 4 초가 걸릴 것입니다.

이 방법은 프로그램과 관련이 있습니다. 입력 또는 절전 모드를 대기중인 프로그램은 프로세서 시간을 사용하지 않기 때문에 (finish-start)의 결과는 0이됩니다.

#include <iostream> 

#include <chrono> // std::chrono::seconds, milliseconds 
#include <thread> // std::this_thread::sleep_for 

#include <ctime> // std::clock() 

int main() { 
    auto start_processor_usage = std::clock(); 
    auto start_wall_clock = std::chrono::steady_clock::now(); 

    std::this_thread::sleep_for(std::chrono::seconds(1)); 

    auto finish_processor_usage = std::clock(); 
    auto finish_wall_clock = std::chrono::steady_clock::now(); 

    std::cout << "CPU usage: " << (finish_processor_usage - start_processor_usage)/CLOCKS_PER_SEC << '\n'; 
    std::cout << "Wall clock: " << (finish_wall_clock - start_wall_clock)/std::chrono::milliseconds(1) << '\n'; 
} 

위의 프로그램해야한다과 같은 결과물을 출력 할 것입니다 일반적으로 * nix에서 스크립트 플랫폼이 제대로 프로세서 사용량을 반환 clock()을 구현하면서, 윈도우하지 않는

CPU usage: 0 
Wall clock: 1000 

하는 것으로. Windows의 경우 clock()은 벽시계 시간을 반환합니다. Windows와 다른 플랫폼간에 전환 할 때이를 명심해야합니다.


확인을 확인합니다. <random>을 사용하는 무작위 int의 구문은 무엇입니까? - Noguiguy

#include <random> 

int main() { 
    // initialize with random seed 
    std::random_device r; 
    std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()}; 
    std::mt19937 engine(seed); 

    // define distribution: improved version of "% 4 + 1" 
    auto one_to_four = std::uniform_int_distribution<>(1, 4); 

    // generate number 
    auto actualNumber = one_to_four(engine); 
} 
+0

앞으로는 확실히 사용하겠습니다. 감사! – Noguiguy

0

나는 또한 내가 원하는 결과를 제공하지 않습니다 시계()를 찾을 수 있습니다. 그래서 난 그냥 그냥이 시도

리눅스

의 지속 시간 Windows에서 QueryPerformanceCounter에를 사용하여 계산 및 위해 clock_gettime을 할 수있는 간단한 타이머 클래스를 썼다 : https://github.com/AndsonYe/Timer

:

관련 문제