2017-05-24 40 views
-4

我正在寫一個有點像算命先生的代碼,但我在switch語句中遇到了一些麻煩。執行代碼時會打印出相同的消息,並且不會像選擇它那樣隨機選擇一個!有人可以幫幫我嗎!謝謝! 繼承人我的代碼C++需要幫助,隨機開關語句

#include<iostream> 
#include<time.h> 
#include<stdlib.h> 

using namespace std; 

void printGreeting(); // function prototype 

int main() 
{ 
    int choice; 
    printGreeting(); 
    cout << "Would you like to see your fortune?" << endl; 
    cout << "Press 1 to see your fortune or 2 if you don't!" << endl; 
    cin >> choice; 

    if (choice == 1) 
    { 
     cout << "Great! Your fortune is: "; 
     // Function to generate random number 
     void rand1(); 
     srand(time(NULL)); 
     int MAX_NUM; 
     MAX_NUM = 5; 
     int random = rand() % MAX_NUM; 
     cout << random << endl; 

     int selection; 
     selection = 5; 

     switch (selection) 
     { 
      case 1: 
       cout << "Change can hurt, but it leads a path to something better!"; 
       break; 
      case 2: 
       cout << "If you have something good in your life don't let it go!"; 
       break; 
      case 3: 
       cout << "You're in for a treat today."; 
       break; 
      case 4: 
       cout << "Land is always on the mind of a flying bird"; 
       break; 
      case 5: 
       cout << "A dream you have will come true"; 
       break; 
     } 

     return 0; 
    } 
    else if (choice == 2) 
    { 
     cout << "Okay goodbye!" << endl; 
    } 
} 

// Prints greeting message 
void printGreeting() // function header 
{ 
    cout << "Hello! Welcome to your fortune teller!" << endl; // function body 
} 
+2

總是調試你的代碼。逐步瞭解'random'的值以及哪個case語句被調用?你會自己想出這個方法。 – FortyTwo

+2

解決這些問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,你應該[編輯]你的問題,以包含一個[Minimal,Complete,and Verifiable](http://stackoverflow.com/help/mcve)例子來重現你的問題,以及你在調試器中所做的觀察。 –

+0

也許你應該使用爲選擇生成的隨機數... – drescherjm

回答

0

因爲selection = 5;

你要選擇selection與1之間的隨機值 - 5,對不對?

+0

是的,這正是我需要它做的。 –

+0

Hi @Zain N. Hi,如果這個或任何答案已經解決了您的問題,請考慮通過點擊複選標記來接受它。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 – FortyTwo

+0

'selection = rand()%5 + 1; //選擇範圍1到5'。閱讀更多關於生成隨機數字[這裏](http://www.cplusplus.com/reference/cstdlib/rand/) – FortyTwo

0

您切換由selection變量,交換機本身前右明確設置爲5。考慮通過random變量進行切換。