这个程序在C中出了什么问题?

时间:2015-12-19 15:33:51

标签: c

我是C编程的初学者,我不明白C中这个简单程序有什么问题。我不希望程序停止,然后我创建一个goto语句让它继续。问题是程序永远不会停止(即使我按2)。这是源代码:

    #include <stdio.h>

int 
main(){

int i , num , d , times ,a ;
float next;
printf("Choose a number: ");
scanf("%i" , &num);

printf("Repeat number ... times: ");
scanf("%d" , &times);

for(i=0; i<times; i++){
    printf("%i\n" , num);
}

printf("Do you want to continue? (1=Yes   2=No) :");
scanf("%a" , &next);

if(a=1){
    goto jump;
}
else if(a=2){
    return 0;
}
else{
    printf("Invalid value");
    goto error;
}
jump:
    printf("Choose a number: ");
scanf("%i" , &num);

printf("Repeat number ... times: ");
scanf("%d" , &times);

for(i=0; i<times; i++){
    printf("%i\n" , num);
}

printf("Do you want to continue? (1=Yes   2=No) :");
scanf("%a" , &next);

if(a=1){
    goto jump;
}
else if(a=2){
    return 0;
}
else{
    printf("Invalid value");
    goto error;
}

error:
printf("Do you want to continue? (1=Yes   2=No) :");
scanf("%a" , &next);

if(a=1){
    goto jump;
}
else if(a=2){
    return 0;
}
else{
    printf("Invalid value");
    goto error;
}
}

3 个答案:

答案 0 :(得分:2)

问题在于您比较数字的方式。在第21行,您检查了用户是否要继续使用以下代码:

Date, Dev7, Dev13, Dev14
2015-01-01, 5.2, 13200, 540
2015-01-02, 5.6, 11200, 570
2015-01-03, 5.3, 13700, 660
2015-01-04, 4.7, 14200, 590
2015-01-05, 4.9, 0, 700

比较运算符为if(a=1){ goto jump; 。使用==,您将1分配给变量a。任何非0值都被评估为true,因此您的代码所做的是将1分配给a,检查a是否为0,并转到跳转。

答案 1 :(得分:1)

问题是你的scanf读取了一个字符串或一个字符串,而这个字符串填入了next,但当你试图控制用户选择时,next你控制a的价值。尝试使用以下代码更改代码:

scanf("%d", &a);

...

if (a == 1) ...

请记住,一个等号(=)是赋值,双等号(==)正在测试是否相等。

答案 2 :(得分:0)

scanf("%a" , &next);
**scanf("%f" , &next);**

scanf("%i" , &num);
**scanf("%d" , &num);**



if(a==1){
    goto jump;
}
else if(a==2){
    return 0;
}

for(i=0; i<times; i++){
    printf("%d\n" , num);
}