二级C语言操作例题(六)

本文提供了三个C语言编程题目,包括字符串转换、字符统计和浮点数四舍五入。第一题涉及将字符串转换为整数并相加,第二题要求统计字符串中大写字母和小写字母的数量,第三题则需实现保留浮点数两位小数并四舍五入的功能。通过这些题目,读者可以加深对C语言数值操作和字符串处理的理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、程序填空题

在此程序中,函数fun的功能是将a和b所指的两个字符串分别转换成面值相同的整数,并进行相加作为函数值返回,规定字符串中只含9个以下数字字符。

例如,主函数中输入字符串”32486”和”12345”,在主函数中输出的函数值为44831。

#include  <stdio.h>

#include  <string.h>

#include  <ctype.h>

#define  N  9

long  ctod( char  *s )

{ long  d=0;

  while(*s)

    if(isdigit( *s))  {

/**********found**********/

      d=d*10+*s-__1__;

/**********found**********/

      __2__;  

 }

  return  d;

}

long  fun( char  *a, char  *b )

{

/**********found**********/

  return  __3__;

}

void main()

{ char  s1[N],s2[N];

  do

  { printf("Input  string  s1 : "); gets(s1); }

  while( strlen(s1)>N );

  do

  { printf("Input  string  s2 : "); gets(s2); }

  while( strlen(s2)>N );

  printf("The result is:  %ld\n", fun(s1,s2) );

}

答案:(1) '0' (2) s++ (3) ctod(a)+ctod(b)

二、程序修改题

在此程序中,fun函数的功能是:分别统计字符串中大写字母和小写字母的个数。

例如,给字符串s输入:AAaaBBbb123CCcccd,则应输出:upper=6,lower=8。

#include <stdio.h>

/**********found**********/

void fun ( char *s, int a, int b )

{

  while ( *s )

  {  if ( *s >= 'A' && *s <= 'Z' )

/**********found**********/

       *a=a+1 ;

     if ( *s >= 'a' && *s <= 'z' )

/**********found**********/

        *b=b+1;

     s++;

  }

}

void main( )

{  char   s[100];  int   upper = 0, lower = 0 ;

   printf( "\nPlease a string :  " );  gets ( s );

   fun ( s,  & upper, &lower );

   printf( "\n upper = %d  lower = %d\n", upper, lower );

}

答案:(1) void fun ( char *s, int *a, int *b ) (2) *a=*a+1; (3) *b=*b+1;

三、程序设计题

在此程序中,编一个函数float fun(double h),该函数的功能是:使变量h中的值保留两位小数,并对第三位进行四舍五入(规定h中的值为正数)。

例如,若h值为1234.567,则函数返回1234.5670000;若h值为1234.564,则函数返回1234.560000。

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

float fun (float h )

{

    

}

void main()

{

  FILE *wf;

  float a;

  system("CLS");

  printf("Enter a: ");

  scanf ("%f",&a);

  printf("The original data is :  ");

  printf("%f\n\n", a);

  printf("The  result : %f\n", fun(a));

/******************************/

  wf=fopen("out.dat","w");

  fprintf(wf,"%f",fun(8.32533));

  fclose(wf);

/*****************************/

}

答案:

long t;

t=(h*1000+5)/10;      /*单精度数h乘以1000后再加5,相当于对h中的第三位小数进行四舍五入除以10后将其赋给一个长整型数时就把第三位小数后的数全部截去*/

return (float)t/100;  /*除以100,保留2位小数*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值