【问题标题】:Hex, binary, and oct to dec converter doesn't work properly C++十六进制、二进制和八进制到十进制转换器无法正常工作 C++
【发布时间】:2017-06-04 01:09:31
【问题描述】:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

long fromBin(long n)
{
    long factor = 1;
    long total = 0;

    while (n != 0)
    {
        total += (n%10) * factor;
        n /= 10;
        factor *= 2;
    }

    return total;
}

int main() {
    int a,b;
    while (true) {
        cin>>a;
        if(a==2){
            cin>>b;
            cout<<fromBin(b)<<endl;
        }
        if(a==16){
            cin >> hex >> b;
            cout << b << endl;
        }
        if(a==8){
            cin>>b;
            cout<<oct<<b<<endl;
        }
    }
}

所以我的任务很简单,但由于某种原因它不起作用。我必须在输入中输入 2 个数字。第一个显示我希望数字 (16,2,8) 转换为十进制的基数第二个数字是数字。我在任务中的例子是: 2 1111;16 F;8 1 ;答案应该是 15,15,1 。你也会认为它必须是一个无限循环,因为我的老师如何检查他的例子,他希望我们是无限循环。我得到正确的答案,但只有我输入一次数字,第二次时间出了点问题,我不明白是什么。例如:当我输入 16 f 时,我得到 15,但是当我再次尝试输入时没有输出,当我尝试输入 2 1111 时,我得到65 没有明显的原因。另一个例子是当我输入 8 1 并且我得到 1(这是正确答案)然后我输入 2 1111 并得到 17.Again 错误。无论我做什么我都不能连续输入 2 16 f,第二个没有给我答案。所以你能帮帮我吗?

【问题讨论】:

  • 有人有想法吗?
  • 天哪,我需要一些帮助:D

标签: c++ hex decimal converter


【解决方案1】:

您使用hexoct 更改cincout 的状态,但是完成后您没有将它们设置回来,所以在下一次通过时,它会做错事.此外,您没有任何代码可以退出任何类型的错误,因此当有人试图退出时,您的代码会发疯。

这里是固定的:

int main() {
    int a,b;
    while (!cin.fail()) // stop after an error
    {
        cin>>a;
        if(a==2){
            cin>>b;
            cout<<fromBin(b)<<endl;
        }
        if(a==16){
            cin >> hex >> b;
            cin >> dec; // put it back the way we found it
            cout << b << endl;
        }
        if(a==8){
            cin>>b;
            cout<<oct<<b<<endl;
            cout<<dec; // put it back the way we found it
        }
    }
}

【讨论】:

  • while(cin &gt;&gt; a) 会更好。第一次输入可能会发生错误或 EOF(如果输入是从文件重定向的),并且 a 将在第一次通过时未初始化。顺便说一句,你刚刚打败了我。两天没有回答,当我开始回答时...... :^)
猜你喜欢
  • 1970-01-01
  • 2015-12-12
  • 1970-01-01
  • 2020-06-27
  • 2011-08-21
  • 2018-04-03
  • 2014-10-30
  • 2015-09-06
  • 1970-01-01
相关资源
最近更新 更多