计算机二级-C语言-字符数字转化为整型数字。形参与实参类型相一致。double类型的使用。

时间:2022-01-02 01:58:21

//函数fun功能:将a和b所指的两个字符串分别转化成面值相同的整数,并进行相加作为函数值返回,规定只含有9个以下数字字符。

//重难点:字符数字转化为整型数字。

 #include  <stdio.h>
#include <string.h>
#include <ctype.h>
#define N 9
long ctod( char *s )
{ long d=;
while(*s)//指针指向字符串首地址。
if(isdigit( *s)) {//此函数检查参数是否为字符整数类型。
/**********found**********/
d=d*+*s-'';//转化为整型类型。
/**********found**********/
s++;
}
return d;
}
long fun( char *a, char *b )
{
/**********found**********/
return ctod(a)+ ctod(b);
}
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) );
}

//函数fun功能:分别统计字符串大写字母和小写字母的个数。

//重难点:形参与实参类型相一致。

 #include <stdio.h>
/**********found**********/
void fun ( char *s, int *a, int *b )
{
while ( *s )
{ if ( *s >= 'A' && *s <= 'Z' )
/**********found**********/
*a=*a+ ;
if ( *s >= 'a' && *s <= 'z' )
/**********found**********/
*b=*b+;
s++;
}
} void main( )
{ char s[]; int upper = , lower = ;
printf( "\nPlease a string : " ); gets ( s );
fun ( s, & upper, &lower );
printf( "\n upper = %d lower = %d\n", upper, lower );
}

//函数fun功能是:使变量h中的值保留两位小数,并对第三位进行四舍五入

//重难点:切记这里使用double类型,使用float会导致不准确。

 #include <stdio.h>
#include <conio.h>
#include <stdlib.h>
double fun (double h )//切记这里使用double类型,使用float会导致不准确。
{//第一种方法:
/* double p;
int s,a;
p = h * 1000;
s = p;
a = s % 10;
if (a > 4) s = s + 1;
p = s;
return p/1000;*/
int s,n,n1,n2,n3;//第二种方法:
double p,q;
s = h;
p = h - (double)s;
p = p * ;
n = p;
n1 = n / ;
n2 = n % / ;
n3 = n % ;
if (n3 > ) n2 = n2 + ;
q = (double)s + ((double)n1 / ) + ((double)n2 / );
return q;
}
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);
/*****************************/
}