第14周練兵區編程題
1. 學生成績管理系統V5.0
2. 字符串中的字符排序
題目內容:
編寫一個函數,對一個字符串中的字符進行升序排序,並輸出字符排序後的字符串,字符串長度小於20。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int mycmp(const void* a,const void* b)
{
const char* x = (const char*)a;
const char* y = (const char*)b;
if(*x - *y == 0)
return 0;
else if(*x - *y > 0)
return 1;
else
return -1;
}
int main()
{
char str[20];
printf("Input a string:\n");
gets(str);
qsort(str,strlen(str),sizeof(char),mycmp);
puts(str);
return 0;
}
3. 純數字字符串檢驗
題目內容:
按給定函數原型編程檢查一個字符串是否全由數字組成。
int IsAllDigit(char p[]);/若全由數字組成,則函數返回1,否則返回0/
#include<stdio.h>
#include<ctype.h>
int IsAllDigit(char p[])
{
int flag = 1;
char *q = p;
while(*q != '\0')
{
if(!isdigit(*q))
flag = 0;
q++;
}
return flag;
}
int main()
{
char str[20];
printf("Please input a string:\n");
gets(str);
if(IsAllDigit(str))
printf("The string is digit string.");
else
printf("The string is not digit string.");
return 0;
}
4. 孿生素數
題目內容:
相差爲2的兩個素數稱爲孿生素數。例如,3與5,41與43等都是孿生素數。設計程序求出指定區間上的所有孿生素數對。區間上限和下限由鍵盤獲取。
#include<stdio.h>
#include<math.h>
int Prime(long n)
{
int i ;
for(i = 2; i <= sqrt(n); i++)
{
if(n%i == 0)
return 0;
}
return 1;
}
int main()
{
long a, b;
int cnt = 0;
printf("please input c,d(c>2):\n");
scanf("%ld,%ld",&a, &b);
for(int i = a; i <= b; i++)
{
if(Prime(i) && Prime(i + 2) && (i + 2 <= b))
{
printf("(%ld,%ld)\n", i, i+2);
cnt++;
}
}
printf("total=%d\n",cnt);
return 0;
}
5. 求解不等式
題目內容:
對指定正實數n(採用雙精度浮點型表示),試求滿足下面平方根不等式的最小整數m,並輸出不等式左邊的值。程序中浮點數的數據類型均爲double。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
double n, sum;
int i, m;
printf("Input n:\n");
scanf("%lf",&n);
for(m = 1; ; m++)
{
sum = 0;
for(i = 0; i <= m; i++)
{
sum += sqrt(m + i);
}
if(sum > n)
{
printf("Result:m>=%d\n",m);
printf("s=%.2f\n",sum);
return 0;
}
}
return 0;
}