简体   繁体   English

Function 添加两个分数和 output 十进制只给出 0

[英]Function to add two fractions and output decimal only giving 0

I'm trying to make a simple program which adds two fractions.我正在尝试制作一个添加两个分数的简单程序。 It takes four numbers as inputs: numerator and denominator of the first fraction and numerator and denominator of the second fraction.它需要四个数字作为输入:第一个分数的分子和分母以及第二个分数的分子和分母。 The output should be the sum of the two fractions in decimal form. output 应该是十进制形式的两个小数之和。 My program isn't working and I'm stuck with how to fix it.我的程序无法正常工作,我不知道如何修复它。 It outputs 0.000 for all of the examples tried to run the function.对于尝试运行 function 的所有示例,它输出 0.000。

# include <stdio.h>

int fracsum(float n1, float d1, float n2, float d2)
{
    float n3, d3;
    double res;
    n3 = (n1*d2) + (d1*n2);
    d3 = d1 * d2;
    res = n3 / d3;
    return res;
}

int main(void)
{
    printf("%.3f %.3f %.3f\n",
       fracsum(1,2,2,4),
       fracsum(1,4,1,8),
       fracsum(4,3,5,6));

    return 0;
}

The output of this code is: 0.000 0.000 0.000此代码的 output 为:0.000 0.000 0.000

int fracsum

but you clearly want但你显然想要

double fracsum

from your printf call来自您的 printf 电话

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM