✔ 最佳答案
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 <iostream>
#include <stdio.h>
#include <stdlib.h>
int main()
{
// This algorithm is definitely NOT very efficient, but here is the code
// In addition, the algorithm is WRONG, because step 4 should read:
// Step 4:Repeat steps 2 and 3 as long as m is NOT LESS THAN x or y.
// The correction is required when x is a multiple of y, such as 48, 24
long n1=-1, n2=-1, product,LCM;
while(n1<=0||n2<=0)
{
printf("Input two positive numbers:");
scanf("%ld",&n1);
scanf("%ld",&n2);
}
product=n1*n2;
// following line is according to algorithm step 4
// while(product>n1&&product>n2) LCM of 27 & 54 would give 108 and not 54
while(product>=n1&&product>=n2)
{
if(product%n1==0&&product%n2==0)LCM=product;
product--;
}
printf("The LCM of %ld and %ld is %d\n",n1,n2,LCM);
system("PAUSE");
return 0;
}
2008-11-26 08:28:34 補充:
What compiler do you use, what is the error message the computer gives?
I am sorry that the additional answers would not give enough space to show the program again.
For the second problem, 001 has given a few useful hints. Here's some more:
2008-11-26 08:28:41 補充:
1. if the number is negative, convert it to positive. Define a variable call sum and set it to zero.
2. use the % (modulus) function to find the last digit. Add it to sum.
3. Divide it by 10 to remove the last digit.
4. repeat 2 and 3 until the number is zero.
PM me if you need more information.