本文介绍了为什么我在C ++中获得不同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{ clrscr();
int m,i=0,a,b[100],c,d[100];
char e='y';
cout<<"\nProgram to convert decimal number into binary number";
loop:if(e=='y'||e=='Y')
{
cout<<"\nEnter a number:";
cin>>a;
do
{
b[i]=a%2;
c=a/2;
a=c;
b[i];
m=i;
i++;
}while(a>=2);
cout<<"\nAnswer:";
cout<<c;
for(i=m;i>=0;i--)
{ cout<<b[i];
}
cout<<"\nDo you want to continue:y/Y or n/N:";
cin>>e;
goto loop;
}
else
{ cout<<"\nThank you for using the decimal to binary converter in C++";
}
getch();
}
当我输入前面带有0的任何数字时,我得不到正确答案。输出搞砸了。
示例:
When I enter any number preceded with 0. I do not get a correct answer. The output is messed up.
Example:
Input:8
给出正确的输出。
但是
gives correct output.
but
Input:08
给出错误且无关的输出。
请帮助我。谢谢。
gives incorrect and irrelevant output.
Please help me. Thanks.
推荐答案
{
cout<<"\nEnter a number:";
到
to
{
i = 0;
cout<<"\nEnter a number:";
shoud修复它。
但是,有一些麻烦:你的代码是简直就是一团糟。此外,它看起来你正在使用一个过时的 C ++
编译器。
你可以这样写你的程序:
shoud fix it.
However, there are troubles at the horizon: your code is simply a mess. Moreover it looks you are using an outdated C++
compiler.
You could write your program this way:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
while ( true)
{
vector <int> binary;
int n;
cout << "please insert a positive number (a negative one to exit)" << endl;
cin >> n;
if ( n < 0) return 0;
do
{
binary.push_back( n % 2);
n >>= 1;
} while (n>0);
for (vector<int>::reverse_iterator rit = binary.rbegin(); rit != binary.rend(); ++rit)
{
cout << *rit;
}
cout << endl;
}
}
这篇关于为什么我在C ++中获得不同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!