標題:
C program 程式問題
發問:
1.The LCM(Lowest Common Multiple) of two numbers x, y is the smallest whole number which is divisible by x and y. The following algorithm istrivial though it is not the most efficient.Step 1: Store x*y to mStep 2:If m is divisible by both x and y, store m to LCMStep 3:Decrease m by 1Step 4:Repeat... 顯示更多 1. The LCM(Lowest Common Multiple) of two numbers x, y is the smallest whole number which is divisible by x and y. The following algorithm is trivial though it is not the most efficient. Step 1: Store x*y to m Step 2:If m is divisible by both x and y, store m to LCM Step 3:Decrease m by 1 Step 4:Repeat steps 2 and 3 as long as m is greater than both x and y. Step 5:Output LCM Write a C program to input two positive numbers and find their LCM. The program should give the following sample output: Enter two numbers: 12, 18 The LCM of 12 and 18 is 36 2.Write a program that find the sum of the digits of a number entered through the keyboards. Your program should cater for both positive and negative numbers. examples: Enter a number : 2511 sum of digits = 9 Enter a number : -2511 sum of digits = 9 更新: 001 - 答非所問,你講緊嘢呀? 002 - sorry, 個program 真係run唔到,可唔可以打多次呀,thanks!! 更新 2: 第2题俾少少貼士呀? 主要問题係点樣將輸入x位數字加晒?謝謝! 更新 3: sorry, really don't understand = =
此文章來自奇摩知識+如有不便請留言告知
最佳解答:
Here is the code for question 1. Feel free to PM me if you have questions. I will leave Q2 for you as exercise, make use of guide given by the previous post. Good luck. /* http://hk.knowledge.yahoo.com/question/question?qid=7008112401110 ianianian02 2008-11-24 17:36:39 1. The LCM(Lowest Common Multiple) of two numbers x, y is the smallest whole number which is divisible by x and y. The following algorithm is trivial though it is not the most efficient. Step 1: Store x*y to m Step 2:If m is divisible by both x and y, store m to LCM Step 3:Decrease m by 1 Step 4:Repeat steps 2 and 3 as long as m is greater than both x and y. Step 5:Output LCM Write a C program to input two positive numbers and find their LCM. The program should give the following sample output: Enter two numbers: 12, 18 The LCM of 12 and 18 is 36 */ //#include
其他解答:
1. Step2至4 以for廻圈進行: for (m = x * y; m > x && m > y; m--) Step2的檢查條件: if ((m % x == 0) && (m % y == 0)) 2. 以字串/char陣列儲存用家輸入 以strlen找出用家輸入的字串的長度 如假設輸入的數字並沒有空白, 先測試一下字串中零位元素是否"-" 如零位元素是"-", 則輸出sum of digits為strlen結果減一 否則, 直接輸出strlen作為sum of digits