C语言实验答案
)
2. 编写一个程序,计算一个从键盘输入的整数的各位之和,例如输入的数是5684,该程序计算并显示5+6+8+4的值23。
【答案】
5-1
#include
main( )
{
char ch;
int i;
for (i = 0; i < 10; i++)
{
ch = getchar( );
if ((ch >= 'a') && (ch <= 'z'))
{
ch = ch - 32;
putchar(ch);
}
}
}
5-2
main( )
{
int a, result, remainder, sum, c;
scanf("%d", &a);
printf("\n");
sum = 0;
result = a;
while (result)
{
c = result;
result = c / 10;
remainder = c % 10;
sum = sum+remainder;
printf("%d", remainder);
}
printf("/b=");
printf("the sum is %d\n", sum);
}
实验六 数组(一)
【实验目的】
1. 掌握数组的定义与使用方法;
2. 了解使用数时应注意的问题;
3. 掌握字符串的用法;
4. 熟练掌握关于字符串的常用函数的用法;
【实验内容】
1. 用数组的方法实现程序,程序的功能是:从键盘上输入50个字符,统计其中英文字符、空格字符、数字字符及其他字符的个数,并将统计结果输出。
2. 调试下列程序,并改正其中的错误。程序的功能是:从键盘上输入两个字符串,并判断两个字符串是否相等。
main( )
{
char str1(10), str2(10);
int j, flag;
printf("\n");
scanf(“%s%s”, &str1, &str2);
while (str1[j] = str2[j])
{
j++;
if (str1[j]= ='\0' || str2[j]= ='\0')
{
break;
}
}
if (str1[j]= ='\0'&&str2[j]= ='\0')
{
flag = 0;
}
else
{
flag = 1;
}
if(flag)
{
printf("the two string are equal.");
}
else
{
printf("the two string are not equal.");
}
}
【答案】
6-1
main( )
{
char string[50];
int i, alpha, space, digit, others;
alpha = space = digit = others = 0;
for (i = 0; i < 50; i++)
{
scanf("%c", &string[i]);
}
printf("\n");
for (i = 0; i < 50; i++)
{
if (string[i] >= 'A'&&string[i] <= 'Z'
|| string[i] >= 'a'&&string[i] <= 'z')
{
alpha++;
}
else if (string[i]==' ')
{
space++;
}
else if (string[i] >= '0'&&string[i] <= '9')
{
digit++;
}
else
{
others++;
}
printf("alpha=%d, space=%d, digit=%d, others=%d\n",
alpha, space, digit, others);
}
6-2
main( )
{
char str1[10], str2[10];
int j = 0, flag;
printf("\n");
scanf(“%s%s”, str1, str2);
while (str1[j] == str2[j])
{
j++;
if (str1[j]= ='\0' || str2[j]= ='\0')
{
break;
}
}
if (str1[j]= ='\0'&&str2[j]= ='\0')
{
flag = 1;
}
else
{
flag = 0;
}
if(flag
)
{
printf("the two string are equal.");
}
else
{
printf("the two string are not equal.");
}
}
实验