Advertisement
Guest User

giacomo

a guest
Nov 14th, 2018
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. /* Ricerca di un numero in un intervallo */
  2.  
  3. #include <stdio.h>
  4.  
  5. int main() {
  6.     int min, max, ndc, risposta1, rispostaf, max_min;
  7.     int i = 1;
  8.  
  9.     // Acquisizione dei dati
  10.  
  11.     printf("Dammi un intervallo di ricerca e pensa un numero all'interno dell'intervallo ('min max'): ");
  12.     scanf_s("%d %d", &min, &max);
  13.  
  14.     ndc = (max + min) / 2;
  15.  
  16.     printf("Hai pensato il numero %d giusto (1=si / 0=no) ? ", ndc);
  17.     scanf_s("%d", &risposta1);
  18.  
  19.     if (risposta1 != 0) {
  20.         printf("Ho indovinato in 1 tentativo!\n");
  21.     }
  22.     else {
  23.  
  24.         min = ndc + 1;
  25.         max = ndc - 1;
  26.  
  27.             while (min <= max)
  28.             {
  29.                 ndc = (min + max) / 2;
  30.  
  31.                 printf("Hai pensato il numero %d giusto (1=si', 0=no)?", ndc);
  32.                 scanf_s("%d", &rispostaf);
  33.  
  34.                 if (rispostaf) {
  35.                     printf("Ho indovinato in %d tentativi\n", i);
  36.                     break;
  37.                 }
  38.                 else {
  39.                     i += 1;
  40.  
  41.                     printf("Il numero che hai pensato e' maggiore (1) o minore (0) di %d? ", ndc);
  42.                     scanf_s("%d", &max_min);
  43.  
  44.                     if (max_min)
  45.                     {
  46.                         min = ndc + 1;
  47.                     }
  48.                     else {
  49.                         max = ndc - 1;
  50.                     }
  51.                 }
  52.             }
  53.  
  54.     }
  55.  
  56.     return 0;
  57.  
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement