編寫代碼,演示任意一個字符串從兩端移動,向中間匯聚,並以這樣的形式輸出。windows
#include<windows.h>ide
Sleep(n毫秒)url
延遲n毫秒再輸出spa
代碼:內存
#include<stdio.h>字符串
#include<stdlib.h>get
#include<string.h>string
#include<Windows.h>it
int main()
{
int i = 0;
printf( "輸入字符的個數n:_" );
int n= 0;
scanf( "%d" ,&n);
char *p1 = (char *)malloc(n + 1);
char *p2 = (char *)malloc(n+ 1);
if (p1 == NULL || p2 == NULL)
{
printf( "out of memory\n" );
exit(1);
}
scanf( "%s" , p1);
int len = strlen(p1);
for (i = 0; i < len; i++)
{
p2[i] = '#' ;
}
p2[len] = '\0' ;
int left = 0;
int right =len-1;
printf( "%s\n" ,p2);
while (left <= right)
{
Sleep(1000); //睡上一秒,再輸出
p2[left] = p1[left];
p2[right] = p1[right];
printf( "%s\n" ,p2);
left++;
right--;
}
free(p1);
free(p2);
system( "pause" );
return 0;
}
或者:
int main()
{
int i = 0;
char p1[100];
char p2[100];
scanf( "%s" , p1);
int len = strlen(p1);
for (i = 0; i < len; i++)
{
p2[i] = '#' ;
}
p2[len] = '\0' ;
int left = 0;
int right = len - 1;
printf( "%s\n" , p2);
while (left <= right)
{
Sleep(1000);
p2[left] = p1[left];
p2[right] = p1[right];
printf( "%s\n" , p2);
left++;
right--;
}
system( "pause" );
return 0;
}
試分析兩個代碼對內存的利用率。
模擬三次密碼登陸:初始密碼123456
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int i = 0;
char arr[10];
while (i < 3)
{
gets(arr);
if (strcmp(arr,"123456" )== 0)
{
printf( "登陸成功\n" );
system( "pause");
return 0;
}
i++;
printf( "登陸失敗\n" );
}
printf( "已經用完三次機會了\n" );
system( "pause");
return 0;
}