一个只能输出数字的代码
#include<stdio.h>
int main()
{
int ch = 0;
while ((ch = getchar()) != EOF)
{
if (ch < '0' || ch>'9')
continue;
putchar(ch);
}
return 0;
}
for 循环
#include<stdio.h>
int main()
{
int i = 0;
for (i = 1; i <= 10; i++)
{
if (i == 5)
break;
printf("%d\n", i);
}
return 0;
}
不可以在for循环体内改变循环变量
建议采用前闭后开写法(i=0;i<10)
for循环的初始化,调整,判断都可以省略,但是如果判断被省略那么条件恒为真。
DO while语句
#include<stdio.h>
int main()
{
int i = 0;
do
{
printf("%d\n", i);
i++;
}
while (i <= 10);
}
计算n的阶乘
#include<stdio.h>
int main()
{
int i = 0;
int ret = 1;
int n = 0;
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
ret = ret * i;
}
printf("ret=%d\n", ret);
return 0;
}
二分法找元素
#include<stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9 ,10};
int k = 6;
int sz = sizeof(arr) / sizeof(arr[0]);
int left = 0;
int right = sz-1;
while(left<=right)
{
int mid = (right + left) / 2;
if (arr[mid] > k)
{
right = mid - 1;
}
else if (arr[mid] < k)
{
left = mid + 1;
}
else
{
printf("ok:%d\n", mid);
break;
}
if (left > right)
{
printf("cuo");
}
}
return 0;
}
找到的数需要加一才是想要的数
#include<stdio.h>
#include<windows.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char arr1[] = "hello word";
char arr2[] = "##########";
int left = 0;
int right = strlen(arr1)-1;
while (left <= right);
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
printf("%s\n", arr2);
Sleep(1000);//休息1秒
system("cls");//cls表示清空屏幕
left++;
right--;
}
return 0;
}
不知道为啥打不出来
#include<stdio.h>
#include<windows.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int i = 0;
char password[20] = { 0 };
for (i = 0; i < 3; i++)
{
printf("请输入密码:>");
scanf("%s", password);
if (strcmp(password, "12345") == 0)//库函数(strcmp)可以用于判断两个字符串是否相等
{
printf("登陆成功\n");
break;
}
else
{
printf("密码错误\n");
}
}
if (i == 3)
printf("请退出\n");
return 0;
}
“==”不能用来判断两个字符串是否相等
回车相当于输入了一个\n
scanf只会读取空格前面的内容
while((ch=getchar())!="\n")
{
;
}
以上代码用于消除“\n”的影响
#include<stdio.h>
int main()
{
char password[20] = { 0 };
int ret = 0;
printf("请输入密码:\n");
scanf("%s", password);
getchar();
printf("请确认(Y/N):>");
ret = getchar();
if (ret == 'Y');
{
printf("确认成功");
};
if(ret=='N')
{
printf("放弃确认");
}
}