gpt4 book ai didi

c - 打印输出 : integer as sum of powers of 2

转载 作者:太空宇宙 更新时间:2023-11-04 06:34:20 26 4
gpt4 key购买 nike

我参加了考试,从那以后我一直在挣扎。您有一个整数数组(例如 13、6、21、4),我需要生成如下所示的输出:

13 = 2^3 + 2^2 + 2^0
6 = 2^2 + 2^1
21 = 2^4 + 2^2 + 2^0
4 = 2^2

这是我到目前为止所得到的。

#include <stdio.h>
#define MAX 100

int main() {
int niz[MAX], nizb, n, i, ones, k;

while(1) {
printf("Array length: ");
scanf("%d", &n);

if (n<=0 || n>MAX) break;

printf("Array elements: ");
for(i=0;i<n;i++){
scanf("%d", &niz[i]);
if (niz[i] <=0) {
printf("Error! Wrong value. Enter new one: ");
scanf("%d", &niz[i]);
}
}

for(i=0;i<n;i++) {
nizb = niz[i];
ones = 0;

for(k=0; k < 16; k++) {
//What should i do here?
}

}

}
}

我被困在这里了。我不知道我应该使用多少位,以及 C 如何看待这些整数位。我正在使用 var 'k' 添加到格式为 '2^3 + 2^2 ...' 的字符串,其中 k 是 'for' 迭代的值。我假设整数的长度是 16,但我真的不确定,因为我们是在一张纸上做的。

我想对大家说声谢谢!!!

最佳答案

您可以使用 sizeof 运算符和 CHAR_BIT 计算要使用的位数:

int bitsPerInt = sizeof(int) * CHAR_BIT;

CHAR_BITlimits.h 中定义。

在你有这个限制之后,你可以使用按位 & 运算符来提取每一位:

for (k = bitsPerInt - 1; k >= 0; k--)
{
if (nizb & (1U << k))
// output
else
// don't
}

我会把细节留给你。

旁白:看起来您正在尝试将 niz 用作数组,但您尚未将其声明为数组。这段代码甚至可以编译吗?另外,main 的返回值应该是int

关于c - 打印输出 : integer as sum of powers of 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675440/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com