分数减少C程序

时间:2014-02-16 00:56:24

标签: 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;
}

3 个答案:

答案 0 :(得分:4)

你在减少循环中无条件地break,所以你永远不会循环多次。你不应该在循环结束时break,这意味着“我们是否找到了gcd,或者我们发现没有工作的除数,停止查看。”

答案 1 :(得分:1)

在这段代码中似乎很可能:

        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子句然后中断(是否{{1} }与break组合或不组合。如果第一次迭代没有减少分数,那么你的意图是循环继续。为实现此目的,printfelseprintf根本不应处于循环中。

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

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

一项重要的技能是学习通过检查循环的执行方式来调试这样的问题。您可以通过在调试器中单步执行程序或插入break语句来报告循环的每次迭代中发生的情况。这将揭示循环只执行一次迭代,无论输入如何。

顺便提一下,有一个更好的算法来减少分数,而不是测试潜在的除数,直到找到一个。它大约有2300年的历史,由Euclid在 Elements ,书(章)VII,命题1和2中描述。

答案 2 :(得分:0)

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");