十进制转二进制C语言版
一、源碼
#include <stdio.h>
?
int main(int argc, const char * argv[]) {
? ? int input = 0;
?? ?
? ? //提示用戶輸入
? ? printf ("請輸入十進(jìn)制數(shù):\n");
?? ?
? ? //接收數(shù)據(jù)
? ? scanf("%d", &input);
?? ?
?? ?
? ? //轉(zhuǎn)換成二進(jìn)制
? ? int temp = input;
? ? int result = 0;
? ? int time = 1;
? ? while (temp != 0) {
? ? ? ? result = temp % 2 * time + result;
? ? ? ? temp = temp / 2;
?? ? ? ?
? ? ? ? time = time * 10;
?? ? ? ?
? ? }
?? ?
? ? //輸出二進(jìn)制數(shù)
? ? printf("%d\n",? result);
?? ?
?? ?
? ? return 0;
}
?
二、要點(diǎn)
在轉(zhuǎn)換階段三種循環(huán)控制語句的選擇:
1.do...while()可以先排除,假如十進(jìn)制為1,則do執(zhí)行一次的操作是多余的
2.for(){}中的循環(huán)控制條件難以確定,for(int temp = input; temp>0; temp = temp/2)這樣也可以,但是想到這個很難
3.while(){}中的循環(huán)條件好控制,也容易想到,應(yīng)為首選項
?
注意:不要碰到循環(huán)就用for,應(yīng)從多個方面考慮
總結(jié)
以上是生活随笔為你收集整理的十进制转二进制C语言版的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工作安排
- 下一篇: 计算机科学 教育部评估,教育部全国第四轮