首页 > 解决方案 > 麻烦制作一个可以告诉我C中两个数字的商的分数和小数形式的计算器

问题描述

编写一个程序,允许用户对整数分数进行乘法和除法,并将结果分数和十进制表示形式提供为带 2 个小数位的双精度数。

我会在下面放一些我尝试过的代码

#include <stdio.h>

int
main(void) {

    int a, b, c, d, g, h, j, k;
    double e, f, l, m, n, o;

    //lets get our inputs//
    printf("Whats the first numerator:");
    scanf_s("%d", &a);

    printf("whats the first denominator(cannot be zero):");
    scanf_s("%d", &b);

    printf("whats the second numerator:");
    scanf_s("%d", &c);

    printf("whats the second denominator(cannot be zero):");
    scanf_s("%d", &d);  

    //calulate the division
    (__int64)e = (a / b);
    (__int64)l = (d / c);
    (__int64)m = e * l;
    //calculate the multiplication
    (__int64)f = (__int64)(a / b) * (__int64)(c / d);
    //im just gonna display the actual value of numerator * numerator 
    g = (a * c);
    //same for the denominator
    h = (b * d);
    //handled the fraction for multiplying so now its time to make the keep change flip

    j = (a * d);
    k = (b * c);

    printf("\n(%d/%d) / (%d/%d): the resulting fraction is %d/%d\nthe decimal representation is %.2f\n", a, b, c, d, j, k, m);

    printf("\n(%d/%d) * (%d/%d): the resulting fraction is %d/%d\nthe decimal representation is %.2f\n\n", a, b, c, d, g, h, f);

    return(0);

}

所以我很确定正在发生的是,我通过将整数转换为双精度值,从 4 字节值变为 8 字节值,但我仍然不知道如何将其转换为更大的字节大小,但是 Visual Studio 说这(__int64)可以解决它。我的分数输出仍然有效,但我的小数始终显示为 0.00,这是因为当转换值从 4 个字节增加到 8 个字节时该值丢失。(如果我对此有任何错误,请纠正我的理解,以便我总体上可以更好地处理comp sci。)

标签: cmath

解决方案


(__int64)f = (__int64)(a / b) * (__int64)(c / d);

这就是问题所在。。

首先,学习使用标准符号而不是 Microsoft 特定的符号,例如 (__int64),它实际上与 long long int 相同,但可能需要在标准工具链上完全替换。其次,您将 double 类型转换为 int,然后想知道小数点到哪里去了。也%d用于整数。如果您没有转换为整数,它仍然不会采用十进制值。

这样的问题会招来反对票。我建议您首先使用调试器调试您的代码。祝你好运 :)

代码就像这个顺便说一句一样简单,

#include <stdio.h>

main(argc,argv)
const char** argv;
{
    int numer1 = 0;
    int denom1 = 0;
    int numer2 = 0;
    int denom2 = 0;
    scanf("%d %d %d %d ",&numer1,&denom1,&numer2,&denom2);    //don't forget zero logic
    double frac1 = (double)numer1/(double)denom1;
    double frac2 = (double)numer2/(double)denom2;
    printf ("Whatever you want to print....");
return 0;
}

还要学会使用好的命名法


推荐阅读