#include<stdio.h>intmain(void){int guess =50;int lower_limit =1;int upper_limit =100;char response;printf("Pick an integer from 1 to 100, I will try to guess it.\n");printf("Respond with a y if my guess is right and with a l if it is larger and with a s if it is smaller.\n");printf("Uh…is your number %d?\n", guess);while((response =getchar())!='y'){if(response =='l'){//猜的太大了
upper_limit = guess;
guess =(lower_limit + upper_limit)/2;printf("Well, then, is it %d?\n", guess);}elseif(response =='s'){//猜的太小了
lower_limit = guess;
guess =(lower_limit + upper_limit)/2;printf("Well, then, is it %d?\n", guess);}while(getchar()!='\n'){continue;}}printf("I knew I can do it!\n");return0;}
8-8
#include<stdio.h>voidmenu();doubleadd(float x,float y);doublesubtract(float x,float y);doublemultiply(float x,float y);doubledivide(float x,float y);intmain(void){menu();float n1, n2;char choice;double result;while((choice =getchar())!='q'){if(choice =='a'|| choice =='s'|| choice =='m'|| choice =='d'){//如果输入了指定的字母,则接下来输入需要计算的数字printf("Enter first number:");while(scanf("%f",&n1)!=1){//若输入的不是数字,则不断提醒用户输入数字,并清空scanf缓存printf("Please enter a number, such as 2.5, -1.78E8, or 3:");while(getchar()!='\n'){continue;}}printf("Enter second number:");while(scanf("%f",&n2)!=1){//若输入的不是数字,则不断提醒用户输入数字,并清空scanf缓存printf("Please enter a number, such as 2.5, -1.78E8, or 3:");while(getchar()!='\n'){continue;}}}else{printf("Please enter the right choice:\n");}switch(choice){case'a':
result =add(n1, n2);printf("%.3lf\n", result);break;case's':
result =subtract(n1, n2);printf("%.3lf\n", result);break;case'm':
result =multiply(n1, n2);printf("%.3lf\n", result);break;case'd':
result =divide(n1, n2);printf("%.3lf\n", result);break;default:break;}while(getchar()!='\n'){continue;}menu();}printf("Bye!");return0;}voidmenu(){printf("Enter the operation of your choice:\n");printf("a. add s. subtract\n");printf("m. multiply d. divide\n");printf("q. quit\n");return;}doubleadd(float x,float y){return x + y;}doublesubtract(float x,float y){return x - y;}doublemultiply(float x,float y){return x * y;}doubledivide(float x,float y){while(y ==0){printf("Enter a number other than 0:");scanf("%f",&y);}return x / y;}