2016-03-13 44 views
-4

我是計算機科學的第一年級學生,目前正在接受Programming的介紹。我們正在學習C編程語言,而且我很難弄清楚如何在代碼末尾正確輸入循環,以詢問用戶是否要繼續。在C編程中,如何使用循環來詢問用戶是否要繼續?

這個簡單的任務要求開發一個程序,該程序將確定員工的總工資(包括「if」語句以確定加班時間)。正如你在我的代碼中看到的那樣,我認爲我做得正確。該任務繼續說明,在我的程序結束時,我應該使用一個循環來詢問用戶是否要繼續。

在課上,我們討論了For循環和While循環,但是我對如何正確實現這個特性有點遺憾。

我最初嘗試做這樣的事情......

printf("Would you like to continue? (1 = Yes, 2 = No) \n"); 
scanf("%i", _____); While (_____ == 'y' || ______ == 'Y') { 
} 

但不知道該怎麼申報爲輸入(scanf函數)或放什麼在while循環。請幫忙。我的春假,沒有校園輔導。謝謝!

這裏是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 

int main() { 
    double totalHours, rate, grossPay, overTime, overTimepay, otHours, grossPaywithOT; 

    //1. I began by asking user for total hours & getting input 
    printf("Enter your total hours worked : \n"); 
    scanf("%lf", &totalHours); 

    //Now I'm using a selection statement to determine pay for overtime hours 
    if (totalHours > 40) { 
     //a. Inform user they have overtime hours 
     printf("You worked over 40 hours this period. \n"); 

     //b. Ask how many hours over 40 they worked 
     printf("How many hours over 40 did you work? : \n"); 
     scanf("%lf", &otHours); 

     //c. Ask the user for hourly rate 
     printf("What is your hourly rate? : \n"); 
     scanf("%lf", &rate); 

     //d. Overtime Rate Calculation & Gross Pay Calculation 
     grossPay = totalHours * rate; 
     overTime = 1.5 * rate; 
     overTimepay = otHours * overTime; 
     grossPaywithOT = overTimepay + grossPay; 

     //e. Display overtime pay and Gross Pay 
     printf("Your overtime pay is %.02lf \n", overTimepay); 
     printf("Your total Gross Pay including overtime is %.02lf \n", grossPaywithOT); 
    } else { 
     //2. Ask the user for hourly rate 
     printf("What is your hourly rate? : \n"); 

     //3. User input for hourly rate 
     scanf("%lf", &rate); 

     //4. Gross Pay Calculation 
     grossPay = totalHours * rate; 

     //5. Display grossPay 
     printf("Your Gross Pay is %.02lf \n", grossPay); 
    } 
} 
+0

的printf(「你願意繼續(1 =是的,2 =否)\ n「); scanf(」%i「,_____); while(_____ =='y'|| ______ =='Y'){// logic printf(」您想繼續?(1 =是,2 =否)\ n「); scanf(」%i「,_____);}您需要詢問用戶是否想在循環中再次繼續,否則您將陷入無限循環,希望幫助 – simon1230756

回答

1

我想:?

char loop='y'; 
while(loop == 'y') { 

    //Do your stuff here 

    printf("do you want to loop? (y/n) "); 
    scanf(" %c", &loop); 
    if(loop != 'y') 
     loop='n'; 
} 

/A

+0

謝謝!這幫助了一大堆。 –

0
do 
{ 
    // loop until they decide to stop 

    // put the code to do your normal stuff here 

    int i = 0; 
    do 
    { 
     // loop until they input a 1 or 2 
     printf("\nWould you like to continue? (1 = Yes, 2 = No) \n"); 
     scanf("%i", &i); 
    } while ((i != 1) && (i != 2)); 

} while (i == 1); 
0

scanf()不寫入變量,但到內存地址。 因此,在你的_____代碼中,你應該寫一個指向內存地址的指針。一對夫婦的例子:

int * intPointer; 
scanf("%i", intPointer); 

或者:

int integer; 
scanf("%i", &integer); 

請注意,您在格式化字符串類型"%i"%i告訴scanf()應該將用戶輸入的字符串解析爲整數。你想把它看作一個角色。 Ç格式化功能(這是最後的˚Fscanf()手段使用%c爲字符

相關問題