【问题标题】:I need to loop this through and have the program terminate when the string -1 is given我需要循环并在给出字符串 -1 时终止程序
【发布时间】:2015-03-24 19:44:01
【问题描述】:
#include <iostream>
#include <cmath>
using namespace std;
int main (){
//Written By: Hannah Stang
//Reads a Binary number and converts it to a decimal
long decimal = 0, remainder, number, base = 1;
long bin;
    cout << "Enter a binary number: ";
    cin >> number;
    bin = number;
    while (number > 0)
    {
        remainder = number % 10;
        decimal = decimal + remainder * base;
        base = base * 2;
        number = number / 10;
    }
cout << "Conversion to decimal: " << decimal << endl;
return 0;
}

我遇到的主要问题是试图让程序运行不止一次。我需要它不断重复,直到我输入 -1 作为值。

【问题讨论】:

  • 你把'while'放错了,你没有检查流状态
  • @DieterLücking 'while' 放置得很好——但是所有东西都需要另一个'while'。

标签: c++ loops binary type-conversion


【解决方案1】:

您可以执行以下操作:

#include <iostream>
#include <cmath>
using namespace std;
int main (){
//Written By: Hannah Stang
//Reads a Binary number and converts it to a decimal
  long decimal = 0, remainder, number, base = 1;
  long bin;
  cout << "Enter a binary number: ";
  cin >> number;
  while (number != -1)
  {
    bin = number;
    while (number > 0)
    {
        remainder = number % 10;
        decimal = decimal + remainder * base;
        base = base * 2;
        number = number / 10;
    }
    cout << "Conversion to decimal: " << decimal << endl;
    cout<< "Enter a binary number: ";
    cin>> number;
  }
  return 0;
}

换句话说,只需将主代码嵌入到条件为数字不等于-1的循环中

请注意,我正在读取循环体末尾的数字,因此如果用户输入 -1,他会立即退出。

【讨论】:

    【解决方案2】:

    尝试移动 while 循环并从 number 初始化为 1 开始:

    long decimal = 0, remainder, number=1, base = 1;
    
    while (number > 0)
    {
        cout << "Enter a binary number: ";
        cin >> number;
        bin = number;
        remainder = number % 10;
        decimal = decimal + remainder * base;
        base = base * 2;
        number = number / 10;
        cout << "Conversion to decimal: " << decimal << endl;
    }
    

    或者你可以这样做:

    while (1)
    {
        cout << "Enter a binary number: ";
        cin >> number;
        if(number == -1)
        {
            cout<<"Program exiting.";
            break;
        }
        bin = number;
        remainder = number % 10;
        decimal = decimal + remainder * base;
        base = base * 2;
        number = number / 10;
       cout << "Conversion to decimal: " << decimal << endl;
    }
    

    【讨论】:

    • 不好 - 即使请求中止也呈现结果,不检查流状态,做作业。
    • @HannahStang 不客气!如果它正常工作,请重复然后请投票或接受我的回答。我不确定 Dieter 在说什么,他的句子对我来说没有意义:P
    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多