Input a positive integer (decimal) and output the binary number corresponding to this integer (implemented with a loop, but without an array or function call).
This article is written in C language. Students in need can refer to it appropriately!
Analysis: How to convert decimal to binary:
Use euclidean division to take the remainder in sequence until the quotient is 0, and the remainder sequence obtained in reverse order is the corresponding binary number , using a loop instead of an array, therefore, an integer value will be formed according to the remainder sequence obtained first, and then the integer value will be output in reverse order (output from low bit to high bit), that is, the binary code will be obtained.
The code is as follows:
#include <iostream> using namespace std; int main() { int n; //待转换的十进制正整数 int m; //存每次转换得到的余数 int sum=0; //进制转换逆序值 int count=0; //记录二进制位数 int i; cout<<"请输入待转换的十进制正整数:"; cin>>n; while(n<0) { cout<<"请重新输入待转换的十进制正整数:"; cin>>n; } cout<<endl; cout<<"十进制"<<n<<"的二进制形式为:"; if(n==0) {cout<<n<<endl; return 0; } while(n!=0) //辗转相除取余到商为0 { m=n%2; //获取对应此次的余数 count++; //二进制位数增1 sum=sum*10+m; //余数按先得到顺序组成一个整数,最后反序就是2进制数 n=n/2; } for(i=count;i>0;i--) //循环从低位到高位逆序输出sum各个位上的数 { cout<<sum%10; sum=sum/10; } cout<<endl; return 0; }
This article is for reference only!
Recommended tutorial: PHP video tutorial
The above is the detailed content of PHP decimal to binary conversion without function. For more information, please follow other related articles on the PHP Chinese website!