【问题标题】:how do i store the value of max(variable)?我如何存储最大值(变量)的值?
【发布时间】:2020-02-18 00:57:20
【问题描述】:

当我运行它并且按下第二个'n'后它不满足逻辑并且原因是max返回0(检查最后一个printf)所以我怎样才能将新值存储在max中?

//A GAME FOR GUESSING YOUR NUMBER BY USING THE BINARY SEARCH ALGORITHM
#include <stdio.h>
int main()
{

int min=1;
int max,z,i;
char ans;

printf("\t\t\t***GUESSING GAME***\n");
printf("Let put a rang, the min number is 1, the max is? \n");
scanf("%d",&max);//--> 15

z=(min+max)/2; //the average


while(i<max)
{
 dis:
 printf("The number is %d? (y/n)\n",z); //--> z =( min(1) + max(15) ) / 2 = 8
 scanf("%s",&ans);

 if(ans=='n')
 {

     printf("Is %d too high? (y/n)\n",z);
     scanf("%s",&ans);
     //new range [1,8]
     if(ans=='y')
     {
         z=(min+z)/2;  //--> z =( min(1) + z(8) ) / 2 = 4
         goto dis;
     }

这个"

     //new range [8,15]
     if(ans=='n')
     {
         z=(z+max)/2; //it should be z =( z(8) + max(15) ) / 2 = 11 
         goto dis;
     }

"

 }
 if(ans=='y')
 {
     printf("\\BINGO/");

max 的值为 0

    // printf("max %d z %d",max,z);

 }
 i++;
}

}

【问题讨论】:

  • 程序具有未定义的行为,因为在循环条件下使用了未初始化的变量 i。而(i
  • 而不是 scanf("%s",&ans);使用 scanf("%c",&ans);在转换说明符之前有一个空格。 %c(不是 %s)

标签: c binary-search


【解决方案1】:

程序有未定义的行为,因为在循环的条件下

while(i<max)
{

使用了一个未初始化的变量i

这个电话

 scanf("%s",&ans);

也会调用未定义的行为,因为在调用scanf 尝试读取字符串时传递了一个字符的地址。例如,如果用户输入'n' scanf 写入寻址内存两个字符'n''\0'。

改为使用

scanf(" %c",&ans);

注意转换说明符%c前的空白。

并且不要使用 goto 语句。而是使用循环。

【讨论】:

    猜你喜欢
    • 2018-08-05
    • 1970-01-01
    • 2017-09-06
    • 2021-03-09
    • 1970-01-01
    • 2021-06-10
    • 1970-01-01
    • 2016-05-26
    • 2011-09-15
    相关资源
    最近更新 更多