我想使用以下代碼獲取用戶輸入:
uint32_t value;
printf("value: ");
scanf("%"SCNu32, &value);
我現在的問題是,我將如何使用用戶輸入(在我的情況下是值),然后在函式 print_binary 中將其格式化為沒有回圈的二進制數回傳?輸出必須是 0b 之后的 32 位。我不能在任何地方使用任何型別的回圈。
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
void print_binary(uint32_t value){
printf("%d = 0b",value);
//I want to print the variable value with a fixed length of 32 and that it is
//binary with the starting index of 0bBinaryValueOfNumber.
return;
}
int main(void) {
uint32_t value;
printf("value: ");
if (scanf("%"SCNu32, &value) != 1) {
fprintf(stderr, "ERROR: While reading the 'uint32_t' value an error occurred!");
return EXIT_FAILURE;
}
printf("\n");
print_binary(value);
printf("\n");
return EXIT_SUCCESS;
}
我也有以下例子:
如果用戶輸入為 5,則該函式應回傳“5 = 0b00000000000000000000000000000101”。
uj5u.com熱心網友回復:
如果你不能使用回圈,你可以使用遞回:
void print_bin(uint32_t n, int digits) {
if (digits > 1) print_bin(n >> 1, digits - 1);
putchar('0' (n & 1));
}
void print_binary(uint32_t value) {
printf("%d = 0b", value);
print_bin(value, 32);
printf("\n");
}
使用尾遞回的替代方法:
void print_bin(uint32_t n, int digits) {
putchar('0' ((n >>-- digits) & 1));
if (digits > 0) print_bin(n, digits);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/361317.html
