【问题标题】:Making fraction output in mixed number format以混合数字格式输出分数
【发布时间】:2017-03-11 22:12:17
【问题描述】:

我制作了一个程序,因此当用户选择选项 1 时,他们可以输入一个分子,然后输入一个分母,如果他们选择选项 2,它将打印该分数。但是我希望它以混合形式打印分数。例如,如果我做了 20/3,它将打印为 6 2/3。关于我将如何解决这个问题的任何帮助?

这是我的代码(希望易于阅读 (:)

#include <stdio.h>
#include <stdlib.h>

//Struct to hold fraction data
typedef struct fraction
{
int numerator, denom;
}fraction;


int main()
{
//Array of 100 fractions
fraction arrFraction[100];

int i = 0, j, num = 1;

//Loop till user want to stop

while (num == 1)
{
    int choice;
    printf("\nPress 1 to enter a fraction\n");
    printf("Press 2 to view stored fractions\n");
    scanf("%d", &choice);


    if(choice == 1)
    {
        //Prompting user
        printf("\nEnter your fraction, numerator followed by denominator\n    ");

        //Reading values from user
        scanf("%d %d", &arrFraction[i].numerator, &arrFraction[i].denom);

        //Incrementing counter
        i++;

    }

    if (choice == 2) {

        for (j = 0; j < i; j++)
        {
            //Printing fractions
            printf("\n  %d / %d \n",  arrFraction[j].numerator,     arrFraction[j].denom);
        }

    }
}//end of while loop



return(0);
}

【问题讨论】:

  • 尝试使用%,如printf("%d %d/%d\n", n/d, n%d, d);
  • 成功了,非常感谢!
  • 那么例如:12/48/6
  • 检查模数是否为0,不显示分数。
  • 仍然:8/6 = 1 2/6 = 1 1/3。没有完全减少?

标签: c arrays loops fractions


【解决方案1】:

您可以使用除法 (/) 和模数 (%) 运算符。

    printf("%d %d/%d",  
      arrFraction[j].numerator / arrFraction[j].denom , 
      arrFraction[j].numerator / arrFraction[j].denom , 
      arrFraction[j].denom
    );

【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2020-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    相关资源
    最近更新 更多