A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© lj61785636 中级黑马   /  2015-5-19 11:25  /  2493 人查看  /  9 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

10黑马币
/*
编写一个函数char_contains(char str[],char c),
如果字符串str中包含字符c则返回数值1,否则返回数值0
*/

#include <stdio.h>
#include <string.h>
int char_contains(char str[],char c)
{

    for (int i = 0; i < size; i++) {            // 第一行
        if (str == c) {
            return 1;
        }
    }
    return 0;

}
int main()
{
    char name[] = "liangjian";
    int size = strlen(name);                    //第二行
    int rusult = char_contains(name,'u');
    printf("%d\n",rusult);

    return 0;
}

题目已经写好了,讲义中的一道题
我这样写无法编译,报错说我的size未定义,可是我再这里不是定义的全局变量size在for中调用吗
怎么会存在未定义问题呢



最佳答案

查看完整内容

size 不是全局变量,是局部变量,char_contains(char str[],char c)函数是无法直接引用的,除非将值传过去。第二个程序,将字符串传递过去,再从字符串中获得size,希望对你有帮助:)

9 个回复

倒序浏览
size 不是全局变量,是局部变量,char_contains(char str[],char c)函数是无法直接引用的,除非将值传过去。第二个程序,将字符串传递过去,再从字符串中获得size,希望对你有帮助:)
回复 使用道具 举报
下面把经过修改后正确的发一下
/*
编写一个函数char_contains(char str[],char c),
如果字符串str中包含字符c则返回数值1,否则返回数值0
*/

#include <stdio.h>
#include <string.h>
int char_contains(char str[],char c)
{
    for (int i = 0; i < strlen(str); i++) {
        if (str[i] == c) {
            return 1;
        }
    }
    return 0;
}

int main()
{
    char name[] = "liangjian";
    int rusult = char_contains(name,'u');
    printf("%d\n",rusult);
    return 0;
}
回复 使用道具 举报
作用域问题,已解决
回复 使用道具 举报
  1. #include <stdio.h>
  2. #include <string.h>
  3. int char_contains(char str[],char c,int size)
  4. {
  5.         int i;
  6.     for (i = 0; i < size; i++) {            // 第一行
  7.         if (str[i] == c) {
  8.             return 1;
  9.         }
  10.     }
  11.     return 0;

  12. }
  13. int main()
  14. {
  15.     char name[] = "liangjian";
  16.     int size = strlen(name);                    //第二行
  17.     int rusult = char_contains(name,'u',size);
  18.     printf("%d\n",rusult);

  19.     return 0;
  20. }
复制代码

你的程序的size的作用范围不对,同时变量i的定义好像也不对把,你的定义方法是java的,在c语言中好像不能用吧!!具体我也不知道,反正我在vc中这样定义变量是不能通过的
回复 使用道具 举报
#include <stdio.h>
#include <string.h>
int char_contains(char str[],char c)
{
       int a=0;      
     for (int i = 0; i < sizeof(str); i++) {
         if (str[i] == c) {
             a=1;
         }
     }
     return a;
}

int main()
{
     char name[] = "liangjian";
     int rusult = char_contains(name,'u');
     printf("%d\n",rusult);
     return 0;
}
回复 使用道具 举报
楼主,这个代码错误好多啊,如果是c语言的话,不能在for循环中定义int类型,同时size也不是全局变量,这个程序的意思也不是要在字符串中找没有c字符,而是找传进去的字符参数
回复 使用道具 举报
size是一个区域变量,你可以定义函数的时候用一个变量传值过去啊
回复 使用道具 举报
请尽快选择最佳答案。
回复 使用道具 举报
size不是全局变量,如果在第1个函数中加一句int size=strlen(str);就应该是对的了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马