2013年计算机二级C语言上机题库二十四_第3页

考试站(www.examzz.com)   【考试站:中国教育考试第一门户】   2013年4月27日
  编程题
  编写函数fun,它的功能是:将一个数字字符串转换为一个整数(不得调用C语言中提供的将字符串转换成整 数的函数。)
  例如 若输入字符串“-1234“,则 函数把它转换为整数值-1234。
  注意:部分源程序给出如下。
  请勿改动主函数main和其他函数中的任何内容,仅在函数fun的花括号中填入所编写的若干语句。
  试题程序:#include <stdio.h>
  #include <string.h>
  long fun ( char *p)
  {
  }
  main()
  {  
  char s[6];
  long n;
  FILE *out;
  char *test[] = {"-1234", "5689", "7102", "-4356"};
  printf("Enter a string:\n");
  gets(s);
  n = fun(s);
  printf("%ld\n",n);
  out=fopen("out.dat", "w");
  for(n=0;n<4;n++)
  fprintf(out, "%ld\n", fun(test[n]));
  fclose(out);
  }
  答案是:
  long fun(char *p)
  {
  long s=0,t;
  int i=0,j,n=strlen(p),k,s1;
  if(p[0]==’-’)
  i++;
  for(j=I;j<=n-1;j++)
  {
  t=p[j]-‘0’;
  s1=10;
  for(k=j;k<n-1;k++)
  t*=s1;
  s+=t;
  }
  if(p[0]==’-’)
  return –s;
  else
  return s;
  }
首页 1 2 3 尾页

相关文章