【问题标题】:C Program not going inside loop for Guess the numberC程序不进入循环猜测数字
【发布时间】:2016-11-19 15:46:46
【问题描述】:

我已经为计算机编写了以下代码来猜测我的号码是多少,我在这里使用了 switch case 语句,它位于 do while 循环中。

当我尝试运行程序时,程序没有进入我的循环,我不知道如何修复它,谁能帮助我吗?

#include<stdio.h>

void main()

{

printf("\n Grenze 1 - Obergrenze. ");

int min=1;

int max;

printf("\n Was ist Obergrenze? ");

scanf("%i",max);

int try=max;

int correct;

int input,i=0;


do{

    correct=max/2;
    printf("Low(1) High(2) oder Correct(3)? \n >");
    start: 
    scanf("%i",input);
    i++;
    switch (input)
    {
       case(1):
       {
        min=min;
        max=max/2;
       } break;


        case(2):
        {
        min=max/2;
        max=max;

        }break;

        case(3):
        {

        goto gotcha;
        }break;

        default:
        {
        printf("\n >");
        goto start;
        }break;

    }



}
while(i<try);



gotcha:

printf("\n Wieder gewonnen!!! Versuche - %i",i);

}

【问题讨论】:

  • 请在调试器中单步调试程序,并告诉我们您认为它应该进入循环但没有进入循环时看到的情况。
  • 这到底是什么意思? ^^,我对编码有点陌生。
  • 最后的while是-while(i
  • 首先停止调用未定义的行为,方法是传递不是指针的内容,并在scanf("%i",max); 中使用具有自动存储持续时间的未初始化变量的值,该值不确定。跨度>
  • 调试器是编程的基本工具。了解如何使用它。没有调试器的程序员就像没有听诊器的医生。

标签: c loops switch-statement


【解决方案1】:

您正在调用未定义的行为,方法是传递非指针并使用具有自动存储持续时间的未初始化变量的值,该值是不确定的,在scanf("%i",max);

scanf("%i",input);也有同样的问题。

使用一元&amp; 运算符将地址传递到likescanf("%i",&amp;max);scanf("%i",&amp;input); 中读取数据。

还请注意,您应该在托管环境中使用标准 int main(void) 而不是 void main(),这在 C89 中是非法的,在 C99 或更高版本中是由实现定义的,除非您有特殊原因使用非标准签名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-22
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多