這10大C語言基礎(chǔ)算法,在面試中會經(jīng)常遇到! 算法是一個(gè)程序和軟件的靈魂,作為一名優(yōu)秀的程序員,只有對一些基礎(chǔ)的算法有著全面的掌握,才會在設(shè)計(jì)程序和編寫代碼的過程中顯得得心應(yīng)手。本文是近百個(gè)C語言算法系列的第二篇,包括了經(jīng)典的Fibonacci數(shù)列、簡易計(jì)算器、回文檢查、質(zhì)數(shù)檢查等算法。也許他們能在你的畢業(yè)設(shè)計(jì)或者面試中派上用場。 1、計(jì)算Fibonacci數(shù)列 Fibonacci數(shù)列又稱斐波那契數(shù)列,又稱黃金分割數(shù)列,指的是這樣一個(gè)數(shù)列:1、1、2、3、5、8、13、21。 C語言實(shí)現(xiàn)的代碼如下: /* Displaying Fibonacci sequence up to nth term where n is entered by user. */#include 結(jié)果輸出: Enter number of terms: 10Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+ 也可以使用下面的源代碼: /* Displaying Fibonacci series up to certain number entered by user. */ #include 結(jié)果輸出: Enter an integer: 200Fibonacci Series: 0+1+1+2+3+5+8+13+21+34+55+89+144+ 2、回文檢查 源代碼: /* C program to check whether a number is palindrome or not */ #include 結(jié)果輸出: Enter an integer: 1232112321 is a palindrome. 3、質(zhì)數(shù)檢查 注:1既不是質(zhì)數(shù)也不是合數(shù)。 源代碼: /* C program to check whether a number is prime or not. */ #include 結(jié)果輸出: Enter a positive integer: 2929 is a prime number. 4、打印金字塔和三角形 使用 * 建立三角形 ** ** * ** * * ** * * * * 源代碼: #include 如下圖所示使用數(shù)字打印半金字塔。 11 21 2 31 2 3 41 2 3 4 5 源代碼: #include 用 * 打印半金字塔 * * * * ** * * ** * * * ** 源代碼: #include 用 * 打印金字塔 * * * * * * * * * * * * * * * ** * * * * * * * * 源代碼: #include 用 * 打印倒金字塔 * * * * * * * * * * * * * * * * * * * * * * * * * 源代碼: #include 5、簡單的加減乘除計(jì)算器 源代碼: /* Source code to create a simple calculator for addition, subtraction, multiplication and division using switch...case statement in C programming. */ # include 結(jié)果輸出: Enter operator either + or - or * or divide : -Enter two operands: 3.48.43.4 - 8.4 = -5.0 6、檢查一個(gè)數(shù)能不能表示成兩個(gè)質(zhì)數(shù)之和 源代碼: #include 結(jié)果輸出: Enter a positive integer: 3434 = 3 + 3134 = 5 + 2934 = 11 + 2334 = 17 + 17 7、用遞歸的方式顛倒字符串 源代碼: /* Example to reverse a sentence entered by user without using strings. */ #include 結(jié)果輸出: Enter a sentence: margorp emosewaawesome program 8、實(shí)現(xiàn)二進(jìn)制與十進(jìn)制之間的相互轉(zhuǎn)換 /* C programming source code to convert either binary to decimal or decimal to binary according to data entered by user. */ #include 結(jié)果輸出: file:///C:\Users\Administrator.WIN-STED6B9V5UI\AppData\Local\Temp\ksohtml10792\wps4.png 9、使用多維數(shù)組實(shí)現(xiàn)兩個(gè)矩陣的相加 源代碼: #include 結(jié)果輸出: file:///C:\Users\Administrator.WIN-STED6B9V5UI\AppData\Local\Temp\ksohtml10792\wps5.png 10、矩陣轉(zhuǎn)置 源代碼: #include 結(jié)果輸出: file:///C:\Users\Administrator.WIN-STED6B9V5UI\AppData\Local\Temp\ksohtml10792\wps6.png |