我已經撰寫了一個程式,用于測驗一個數字是否是 2 的冪。但是我有問題,我不知道如何解決它。但是我需要制作一個可以測驗更多而不是一個數字的程式。我不知道我是否解釋得很好(因為我不太懂英語)。你有什么建議,我可以在代碼中改變什么?
#include <stdio.h>
//function prototype for checking power of two
int checkPowerofTwo(int n);
int main()
{
int num;
printf("Enter the number you want to test: ");
scanf("%d", &num);
if (checkPowerofTwo(num) == 1)
printf("\n%d is a power of 2\n", num);
else
printf("\n%d is not a power of 2\n", num);
return 0;
}
//function body
int checkPowerofTwo(int x)
{
//checks whether a number is zero or not
if (x == 0)
return 0;
//true till x is not equal to 1
while( x != 1)
{
//checks whether a number is divisible by 2
if(x % 2 != 0)
return 0;
x /= 2;
}
return 1;
}
uj5u.com熱心網友回復:
如果我理解正確,您需要的是一個回圈。例如
int main( void )
{
while ( 1 )
{
int num;
printf("Enter the number you want to test (0 - exit ): ");
if ( scanf("%d", &num) != 1 || num == 0 ) break;
if ( checkPowerofTwo( num ) )
printf("\n%d is a power of 2\n", num);
else
printf("\n%d is not a power of 2\n", num);
}
return 0;
}
請注意,如果用戶輸入負數,您的功能將無法正常作業。
所以最好將變數num和函式引數宣告為無符號型別unsigned int
uj5u.com熱心網友回復:
這樣的事情怎么樣
for (int i = 0; i<1000; i ) {
if (checkPowerofTwo(i) == 1)
printf("\n%d is a power of 2\n", i);
}
測驗代碼?
uj5u.com熱心網友回復:
如何運行以測驗數字是否為 2 的冪?
對于非負整數,有一個技巧可以很快做到這一點:
if( x & (x - 1) == 0) {
// Either zero or a power of 2
}
要還支持負整數,您可以:
if(x > 0) {
if( x & (x - 1) == 0) {
// It's a power of 2
}
} else if(x < 0) {
if( -x & (-x - 1) == 0) {
// It's a power of 2
}
}
請注意,您的原始代碼不支持負數(您可能應該在unsigned int任何地方使用,包括 using scanf("%u", &num);)。
但是我需要制作一個可以測驗更多而不是一個數字的程式。
這是一個不同的問題:
int main() {
unsigned int num;
do {
printf("Enter the positive number you want to test, or 0 to exit: ");
scanf("%u", &num);
if(num == 0) {
return 0;
}
if (checkPowerofTwo(num) == 1) {
printf("\n%u is a power of 2\n", num);
} else {
printf("\n%u is not a power of 2\n", num);
}
} while(1); // Loop forever
}
uj5u.com熱心網友回復:
謝謝你們。我唯一做的就是將 int checkPowerofTwo(int x) 更改為 int checkPowerofTwo(int num),將每個 intiger x 更改為 num,現在它可以作業了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434686.html
