如何使小数到分数计算器工作

时间:2016-05-24 00:22:47

标签: c++

我无法制作一个将小数转换为c ++分数的程序。我已粘贴下面的代码,并对任何建议持开放态度。

int main()
{
    char n = 0;//for decimal point
    char x = 0;//for tenths place
    char y = 0;//for hundredths place
    std::cout << "Please enter the decimal to the hundredths place here: ";
    std::cin >> n;
    std::cin >> x;
    std::cin >> y;
        if (x == 0)
            std::cout << 0 << y << "/100";
        if (y == 0)
            std::cout << x << "/10";

        if (y == 1 || y == 2 || y == 3 || y == 4 || y == 5 || y == 6 || y == 7 || y == 9)
            std::cout << x << y << "/100";

}

2 个答案:

答案 0 :(得分:1)

您正在获取char类型输入,并将其与int值进行比较。尝试比较您使用的int值的char等价物(即&#39; 1&#39;而不是1)。另外,你的最后一个如果排除8的可能性,我认为这很奇怪。

它会给出类似这样的东西:

if (x == '0')
    std::cout << 0 << y << "/100";
if (y == '0')
        std::cout << x << "/10";

    if (y == '1' || y == '2' || y == '3' || y == '4' || y == '5' || y == '6' || y == '7' || y == '8' || y == '9')
        std::cout << x << y << "/100";

答案 1 :(得分:0)

除Bettorun的答案外,您还需要对变量做同样的事情:

#include <iostream>

using namespace std;

int main()
{
        char n = '0';//for decimal point
        char x = '0';//for tenths place
        char y = '0';//for hundredths place

        cout << "Please enter the decimal to the hundredths place here: ";
        cin >> n >> x >> y;

        if (x == '0')
            cout << '0' << y << "/100" << endl;

        if (y == '0')
            cout << x << "/10" << endl;

        else if (y == '1' || y == '2' || y == '3' || y == '4' || y == '5' || y == '6' || y == '7' || y == '9')
        cout << x << y << "/100" << endl;

        return 0;
}