-3

我在做这个练习时遇到了一些麻烦。基本上,function void check(char *tel, char *c)数组的第一个值必须是数字2,其他 8 必须是 之间的数字0 and 9。如果条件满足则打印V,否则打印F

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>

void check(char *tel, char *c){

int i;

if(*tel!=2) printf("Error\n"); 
                *c='F';
                return;  //I guess this return is wrong

if(*tel==2)
    for(i=0;tel[i]<9;i++){
        if(isdigit(tel[i]));

                   else{
               printf("Error!\n");
               *c='F';
               break;
                               return;}         //this one might be in bad use too

    }
 else

 *c='V';           //having troubles here.. i'm not seeing a way to fix this
 }

 int main(){

 char number[9]={2,3,4,5,6,7,4,5,3};
 char car;


 check(number,&car);

 printf("%c \n", car);

     system("pause");
}
4

2 回答 2

5

您的许多ifelse块周围缺少花括号。正确缩进和格式化你的代码会有很长的路要走。

if(*tel!=2) printf("Error\n"); *c='F'; return;

例如,上面应该是:

if (*tel != 2) {
    printf("Error\n");
    *c = 'F';
    return;
}

请,请,请:正确缩进您的代码


编辑:更明确地说,这是您的代码在重新格式化后的样子。你现在看到错误了吗,你缺少花括号的地方?

/*******/提示:我已经用注释标记了应该有它们的行。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

void check (char *tel, char *c) {
    int i;

    if (*tel != 2)                          /*******/
        printf("Error\n"); 

    *c = 'F';
    return;

    if (*tel == 2)                          /*******/
        for (i = 0; tel[i] < 9; i++) {
            if (isdigit(tel[i]))            /*******/
                ;
            else {
                printf("Error!\n");
                *c = 'F';
                break;
                return;
            }
        }
    else                                    /*******/
        *c = 'V';
}

int main() {
    char number[9] = {2, 3, 4, 5, 6, 7, 4, 5, 3};
    char car;

    check(number, &car);

    printf("%c \n", car);

    system("pause");
}
于 2013-03-14T02:22:49.950 回答
4

您发布的代码存在很多小问题。这对我来说是最明显的:

if(*tel!=2) printf("Error\n"); *c='F'; return;  //I guess this return is wrong

由于您决定不使用花括号来分割 if-branch 逻辑,因此只有第一条语句 - printf("Error\n"); 被认为与您的 if 检查相关联。这意味着在每次执行中,c 的值都将设置为 'F' 并且函数将返回。编译器将其视为:

if (*tel != 2) { 
  printf("Error\n");
}
*c = 'F';
return;
// The rest is ignored

您应该显式地使用花括号来标记 if 分支,直到您对 C++ 中的语句定义非常熟悉!

于 2013-03-14T02:23:50.320 回答