C语言课程心得(四)

例题:

1.不使用额外变量的前提下将a,b两个变量的值互换.
(一)加减法:
#include <stdio.h>
int main()
int a=3;
int b=5;
a=a+b;
b=a-b;//原来的a赋给现在的b
a=a-b;//原来的b赋给现在的a
return 0;
}
问题:整型溢出即a+b得到的值可能超过整型的最大限度
(二)异或法:
#include <stdio.h>
int main()
int a=3; 0011
int b=5; 0101
a=a^b; a=0110
b=a^b; b=0011
a=a^b; a=0101
return 0;
}
此时不会溢出因为不会产生进位
一般在企业中会采用第三变量的方法,代码可读性和效率高。
2.给定一个非空整型数组,除了某个元素只出现一次以外,其余每个元素均出现两次,找出那个只出现了一次的元素。
样例:int a[]={1,2,3,4,5,1,2,3,4};该数组中只有5出现一次,其余成对出现,要找出5。
思路:
两次嵌套算每个数出现次数若次数为1则输出。
暴力求解法:
具体代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main(){
int arr[] = {1,2,3,4,5,1,2,3,4};
int i,p;
int count;
for (i = 0; i <= 8; ++i){
count = 0;
for (p = 0; p <= 8; ++p){
if (arr[i] == arr[p]){
count += 1;
}
}
if (count == 1){
printf("%d", arr[i]);
}
}
return 0;
}
巧妙异或法:
首先:
a^a=0 0^a=a
a^b^a=b a^a^b=b (异或具有交换律)
所以1^2^3^4^5^1^2^3^4=1^1^2^2^3^3^4^4^5=5
即可找到落单的那个数字
具体代码:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

int main(){
int arr[] = {1,2,3,4,5,1,2,3,4};
int i;
int sum = arr[0];
for (i = 1; i <= 8; ++i){
sum = sum^arr[i];
}
printf("%d\n", sum);
return 0;
}
时间复杂度:O(n)
但多个单个值就不行了
3.写一个关机程序
程序运行,你的电脑在1分钟后关机,如果输入:我是猪,就取消关机
系统中cmd中输入shutdown -s -t 60(60秒之后关机)为关机的指令
而shutdown -a为取消关机指令
C语言中system("shutdown -s -t 60");
取消用system("shutdown -a");
system需要引入#include <stdlib.h>

strcmp函数

用法:
strcmp(arr1, arr2)
strcmp(arr, "abc")若数组为abc则函数返回0若前小于后返回复数后大于前返回正数
此函数需要加头#include <string.h>
具体函数:
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char arr[] = "";
//system("shutdown -s -t 60");
again:
printf("Your computer is going to shutdown in 60s do something:");
scanf("%s", arr);
if (strcmp(arr,"pig")==0)
{
//system("shutdown -a");
printf("ok");
}
else
{
goto again;
}
return 0;
}

猜你喜欢

转载自blog.51cto.com/15079723/2589169