为什么这段代码没有给出lcm的两个数字? [英] Why this code not giving lcm of two numbers ?

查看:98
本文介绍了为什么这段代码没有给出lcm的两个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不管我们如何用gcd /(a * b)方式​​计算lcm,如何稍微修改这些代码,以便为lcm计算提供临时结果。



我尝试过:



Keeping aside how we calculate lcm by gcd/(a*b) way, how to modify this code slightly such that it gives ad-hoc result for lcm calculation.

What I have tried:

void main()
{
	int a,b,i,v,lcm=1;
	printf("Enter two numbers");
	scanf("%d %d",&a,&b);
    
    	
	while(i<=(a*b))
	{
		if( a%i==0 && b%i==0)
		{
			v= i*lcm;
			i++;
			
		}
		else
		i++;
	
	}
	printf("The lcm is %d",v);
	getch();
}

推荐答案

尝试

Try
#include <stdio.h>

int main()
{
  int a,b,lcm;
  printf("Enter two numbers\n");
  scanf("%d %d",&a,&b);


  lcm = a > b ? a : b;

  while(lcm <= (a*b) )
  {
    if( lcm%a==0 && lcm%b==0)
    {
      break;
    }
    ++lcm;
  }
  printf("The lcm is %d\n",lcm);
  getchar();
  return 0;
}


这篇关于为什么这段代码没有给出lcm的两个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆