一、改错题
(1)程序的功能是:换数。例如:输入: 3和9 输出: 9和3
注释error的下一行中有错误
#include "stdio.h"
void main()
{
int x, y, t;
printf("Please input two int numbers:");
//===============error==============
scanf("%d%d",&x,&y );
printf("x = %d, y = %d \n", x, y );
//===============error==============
t=x;x=y;y=t;
printf("x = %d, y = %d \n", x, y );
}
一、改错题
(2)文件prog.c程序的功能是:任意输入一串字符,以“?”结束,
分别统计其中字母、数字、其他字符的个数。
注释error的下一行中有错误
#include <stdio.h>
void main()
{
char c ; int n1=0,n2=0,n3=0;
printf("input characters:");
//===============error==============
while((c=getchar())&&(c!='?'))
{
//===============error==============
if (((c>='a')&&(c<='z'))||((c>='A')&&(c<='Z')))n1++;
else if(c>='0'&&c<='9')n2++;
else n3++;
}
printf("n1=%d, n2=%d, n3=%d\n",n1,n2,n3);
}
一、改错题
(3)文件prog.c程序的功能是:是从键盘输入学号,然后输出学号中百位数字是3的学号,输入0时结束循环。
注释error的下一行中有错误
#include <stdio.h>
void main()
{
long int num;
scanf("%ld",&num);
//========== error ===========
while(num)
{
//========== error ===========
if((num%1000)/100==3)
printf("\n%ld\n",num);
scanf("%ld",&num);
}
}
二、编程题
(1)利用函数average()求一组数去掉一个最大数和去掉一个最小数后的平均数,
请编写average()函数。
#include <iostream>
using namespace std;
double average(double a[],int n)
{
double min=a[0],max=a[0],sum=0.0;
for(int i=0; i<n; i++)
{
if(a[i]<min)
{
min=a[i];
}
if(a[i]>max)
{
max=a[i];
}
sum+=a[i];
}
return (sum-min-max)/(n-2);
}
int main()
{
double a[10]= {0,1,2,3,4,5,6,7,8,9};
cout<<"去除最大最小后的平均数:"<<average(a,10)<<endl;
return 0;
}
运行结果:
二、编程题
(2)程序<<<QN>>>利用函数fun()使数组a上半三角元素中的值全部置为0,
请编写函数void fun(int a[ ][N]),例如
| 1 9 7 | | 0 0 0 |
a= | 2 3 8 | ,则返回主程序后a数组中的值应为 | 2 0 0 |
| 4 5 6 | | 4 5 0 |
#include <iostream>
using namespace std;
#define N 3
void fun(int a[ ][N])
{
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
if(i<=j)
a[i][j]=0;
}
int main()
{
int a[N][N]= {0};
cout<<"输入矩阵:"<<endl;
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
cin>>a[i][j];
fun(a);
cout<<"\nTHE RESULT\n";
for(int i=0; i<N; i++)
for(int j=0; j<N; j++)
{
cout<<a[i][j]<<" ";
if(j==N-1)
cout<<endl;
}
return 0;
}
运行结果:
二、编程题
(3)程序利用函数primecount()求一组数中的质数个数,请编写primecount()函数。
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
int primecount(int a[],int n)
{
int count=0,flag;
for(int i=0; i<n; i++)
{
flag=1;
if(a[i]==1)
flag=0;
else
{
for(int j=2; j<=sqrt(a[i]); j++)
{
if(a[i]%j==0)
{
flag=0;
break;
}
}
}
if(flag==1)
count++;
}
return count;
}
int main()
{
int a[10]= {1,2,3,4,5,6,7,8,9,10};
cout<<"10以内的素数:"<<primecount(a,10)<<"个"<<endl;
return 0;
}
运行结果: