使用C中的数组输入分数

时间:2016-10-28 21:04:18

标签: c arrays fractions

我的程序会在用户之后询问分子,然后是分母(如果选择了选项1)。我很确定我的部分是正确的。当我点击选项2时,我似乎无法弄清楚如何显示分数。

这是我的代码:

#include<stdio.h>
#include<string.h>

typedef struct fraction
{
int numerator, denom;
} fraction; //defined the fraction.

int main()
{//start of program 

int z = 0;
int y = 0;

 while (1) 
    { //start of while loop 
    int choice;
    printf("\nPress 1 to enter a fraction\n"); 
    printf("Press 2 to view the entered fraction\n");

    scanf("%d", &choice);

    fraction arrFraction[100];

    arrFraction[0].numerator = 0;
    arrFraction[0].denom = 0;

    if (choice == 1) // first option (enter numerator and then denom after)
    {
        printf("Enter the fraction\n");
        scanf("%d", &arrFraction[y].numerator);
        scanf("%d", &arrFraction[z].denom);
     y++    
     z++;

    }// end of first if statement(to enter the fraction)

    if (choice == 2) //to view the entered fractions.
    {
        printf("\n-----------------------------");

        for (int m = 0; m < z; m++)
        {
            printf("  %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
        }
        printf("\n\n-----------------------------");
    } // end of second if statement (to view the fraction entered earlier)
      } // end of while loop

system("pause");
return(0);

}

1 个答案:

答案 0 :(得分:0)

您需要将fraction arrFraction[100];移出while循环,否则,每次迭代都会有一个新数组。

那就是说,

 printf("  %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);

是错误的,你提供两个格式说明符但只有一个参数。这会调用screenshotOfRequestWithResponseHeaders。你的编译器应该警告过你。

我相信,你想要的是

 printf("  %d / %d \n", arrFraction[y].numerator, arrFraction[z].denom);

那就是说,我对整体逻辑不太相信。为什么你似乎需要一组100元素?如果您只对之前的记录(不是记录)感兴趣,请仅使用简单变量,而不是数组。此外,你不需要有两个单独的索引/计数器。单个索引将能够以简洁和健壮的方式管理输入。