Dalam program, nombor telah dimulakan kepada pemalar tertentu. Di sini kita perlu meminta pengguna meneka nombor yang sudah ada dalam program. Untuk melakukan ini, kami perlu memberikan beberapa petunjuk setiap kali pengguna memasukkan nombor.
Logik untuk meneka nombor ditunjukkan di bawah −
do{ if(num==guess){ flag=0; } else if(guess<num) { flag=1; printf("Your guess is lower than the number</p><p>"); count++; } else { flag=1; printf("Your guess is greater than the number</p><p>"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it</p><p>"); scanf("%d",&guess); } } while(flag);
Berikut ialah program C untuk meneka permainan nombor.
Demonstrasi Langsung
#include<stdio.h> main() { int i,num=64,flag=1,guess,count=0; printf("guess the number randomly here are some clues later</p><p>"); scanf("%d",&guess); do { if(num==guess) { flag=0; } else if(guess<num) { flag=1; printf("Your guess is lower than the number</p><p>"); count++; } else { flag=1; printf("Your guess is greater than the number</p><p>"); count++; } if(flag==1) { printf("sorry wrong enter! once again try it</p><p>"); scanf("%d",&guess); } } while(flag); printf("Congratulations! You guessed the correct number %d</p><p>",num); printf("Total number of trails you attempted for guessing is: %d</p><p>",count); }
Apabila program di atas dilaksanakan, ia menghasilkan output berikut −
guess the number randomly here are some clues later 45 Your guess is lower than the number sorry wrong enter! once again try it 60 Your guess is lower than the number sorry wrong enter! once again try it 70 Your guess is greater than the number sorry wrong enter! once again try it 65 Your guess is greater than the number sorry wrong enter! once again try it 62 Your guess is lower than the number sorry wrong enter! once again try it 64 Congratulations! You guessed the correct number 64 Total number of trails you attempted for guessing is: 5
Atas ialah kandungan terperinci Tulis program C untuk bermain permainan meneka. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!