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;
}
























發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章