1.实现在字符数组中指定位置插入字符
2.实现在字符数组中指定开始位置插入字符串
#include<stdio.h>
#include<string.h>
int main()
{
char str[20] = "hello";
printf("str = %s\n", str);
/* insert a character at the specified position */
int position = -1;
char ch;
int i;
printf("\nInput position\n");
while(position > strlen(str) || position <= 0)
{
printf("position =");
scanf("%d", &position);
}
printf("\nInput character =");
scanf(" %c", &ch);
for(i = strlen(str); i >= position; i--)//从最后一个字符开始,把指定位置之后的字符全往后
{ //推一格
str[i] = str[i-1];
}
str[i] = ch; //替换指定位置上的字符
printf("\nresult = %s", str);
/* insert string at specified starting position */
char ptr[20] = {0};
char ptr2[20] = {0};
position = -1;
strcpy(str, "hello");
printf("\n\nstr = %s\n", str);
printf("\nInput starting position\n");
while(position > strlen(str) || position <= 0)
{
printf("\nstarting position =");
scanf("%d", &position);
}
printf("\nInput string \n");
do
{
printf("string = ");
scanf("%s", ptr);
}while(strlen(str) + strlen(ptr) > 19);
strncpy(ptr2, str, position - 1); //把指定位置之前的字符放在新的数组ptr2中
strcat(ptr2, ptr); //把ptr的字符串连接在ptr2后
strcat(ptr2, str + position-1); //把str剩下的字符串连接在ptr2后
printf("\nresult = %s", ptr2);
return 0;
/***运行结果***/
str = hello
Input position
position =6
position =5
Input character =3
result = hell3o
str = hello
Input starting position
starting position =2
Input string
string = 123
result = h123ello
3.通过编程实现,统计1~n有多少个9
#include<stdio.h>
int fun(int n)
{
int count=0;
if(n%10==9) count=count+1;
if(n/10>0) count=fun(n/10)+count;
return count;
}
int main()
{
int n=0;
int i=0;
int sum=0;
printf("enter a number:");
scanf("%d",&n);
for(i=1;i<n+1;i++)
sum=sum+fun(i);
printf("result=%d\n",sum);
return 0;
}
/****运行结果****/
enter a number:100
result=20
enter a number:200
result=40
enter a number:600
result=120
4.有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的哪位。
#include<stdio.h>
#define LEN 10000
int main()
{
int a[LEN] = {0};
int count = 0;
int num = 0;
int i = 0;
int j = 0;
int m;
printf("Enter the number of people(2-%d):\n", LEN);
while(num < 3 || num > LEN)
{
printf("peoplenumber =");
scanf("%d", &num);
}
m = num;
while(1)
{
if(m == 0)
{
break;
}
if(a[i] == 0)
{
count++;
j = i;
}
if(count == 3)
{
count = 0;
a[i] = 1;
m--;
}
i++;
if(i == num)
{
i = 0;
}
}
printf("\nThe last person's number is: %d\n", j + 1);
return 0;
}
/****运行结果****/
Enter the number of people(2-10000):
peoplenumber =10
The last person's number is: 4
Enter the number of people(2-10000):
peoplenumber =100
The last person's number is: 94
Enter the number of people(2-10000):
peoplenumber =10000
The last person's number is: 2692
5.一个数如果恰好等于它的因子之和,这个数被成为”完数”,例如:6=1+2+3.请编程找出1000以内的完数
#include<stdio.h>
int judgewanshu(int num)
{
int sum = 0;
int i= 0;
while(i < num/2)
{
i++;
if(num % i == 0)
{
sum = sum + i;
}
}
if(sum == num)
{
return 1;
}
return 0;
}
int main()
{
int num;
int count = 0;
printf("wanshu within 1000:\n")
for(num = 1; num <= 1000; num++)
{
if(judgewanshu(num))
{
printf("%d\n",num);
}
}
return 0;
}
/****运行结果****/
6
28
496