馏分减少C程序

  • 本文关键字:程序 c
  • 更新时间 :
  • 英文 :


好吧,伙计们,这是一份家庭作业,但它已经提交,我收到了78:。我的教授还没有回复我的求助电子邮件,所以我现在来了。

代码的第一部分应该将分数简化为其最低形式,并且它很有效。。除非最大公分母大于10。这是对C类的介绍,我对C及其特殊性几乎没有经验。关于GCD问题,有什么帮助/指导/想法吗。。?

#include <stdio.h>
int main (void)
{
int num;
int den;
int x;
int y;
int i;
int a;
int n;
int w;
int j;
printf("n *************Question 1 *************** n");
printf("Please enter the numerator: ");
scanf("%d", &num);
printf("Please enter the denominator: ");
scanf("%d", &den);
printf("The fraction entered is: n %d/%d n", num, den );
if (num > den)
x=den;
else
x=num;
for(i=x; i>=1; i--){
if(num % i == 0 && den % i == 0){
printf("This fraction can be reduced! n");
num = num/i;
den = den/i;
printf("The reduced fraction is %d/%d n n", num, den); break;}
else
printf("This fraction cannot be reduced any further n");
break;
}
printf("n ***************Question 2****************** n");
printf("Please enter a number and I will print the even squares up to your input   ");
scanf("%d", &n);
for ( w=1; w<=n; w++)
if (w*w%2 == 0 && w*w <= n )
printf("%d n", w*w);
printf("Question 5 test... please enter 10.3 then 5 then 6 ");
scanf("%d%f%d",&i,&x,&j);
printf("%d %f  %d n",i,x,j);
return 0;
}

您在归约循环中无条件地break,因此您永远不会循环不止一次。你不应该在循环结束时使用break,这意味着"无论我们找到了gcd,还是找到了不起作用的除数,都不要再看了。">

在这段代码中:

else
printf("This fraction cannot be reduced any further n");
break;

您打算将breakprintf:分组

else
{
printf("This fraction cannot be reduced any further n");
break;
}

然而,无论哪种方式都是不正确的。正如所写的,循环的第一次迭代将执行if的then子句,该子句减少分数并退出循环,或者将执行else子句,然后中断(无论break是否与printf分组)。如果第一次迭代没有减少分数,那么循环将继续。为了实现这一点,elseprintfbreak根本不应该在循环中。

相反,您应该允许循环继续执行迭代,直到它完成,因为then子句中的break以成功的减少终止了它,或者因为for语句中的控制表达式在i达到零时结束了循环。

循环之后,您可以测试i是否为零。这将告诉您循环结束是因为执行了缩减(并且执行了break),还是因为循环耗尽了所有迭代。在后一种情况下,如果您希望打印这样的消息,则可以打印分数无法减少的消息。

一项重要的技能是通过检查循环的执行方式来学习调试这样的问题。您可以通过在调试器中逐步执行程序来实现这一点,也可以插入printf语句来报告循环的每次迭代中发生的情况。这表明循环只执行一次迭代,而不考虑输入。

顺便说一句,有一种比测试潜在除数直到找到一个除数更好的算法来减少分数。它大约有2300年的历史,欧几里得在《元素》第七卷命题1和2中对其进行了描述。

for(i=x; i>1; i--)
{
if(num % i == 0 && den % i == 0)
{
break;
}
}
if ( i > 1 )
{
printf("This fraction can be reduced! n");
num = num/i;
den = den/i;
printf("The reduced fraction is %d/%d n n", num, den);
}
else
printf("This fraction cannot be reduced any further n");

最新更新