【发布时间】:2018-09-23 17:26:54
【问题描述】:
假设输入以无符号幅度和二进制补码形式给出,我正在编写一个程序,它将给定的位串(最多 32 位)转换为十进制。我一次从用户那里读取一个字符并尝试将其存储到一个数组中,但是该数组没有所需的大小。有没有办法让数组在不知道数组大小的情况下通过循环?我还试图找出一种不使用 pow 和乘法函数的方法。我在下面发布我的代码,如果您有任何想法,请
#include "stdio.h"
#include "math.h"
#define MAX_BITS 32
#define ENTER '\n'
#define NUMBER_TWO 2
int main()
{
int unsignedMag;
int twosComp;
int negation[n];
int bitStore[n];
char enter;
//Input from the User
printf("Enter up to 32 bits (hit 'enter' to terminate early): ");
//Reads the first bit as a character
char bit = getchar();
while (getchar != enter) {
bit = bit - '0';
scanf("%c", &bitStore[bit]);
getchar();
}
//Terminates if user hits enter
if (bit == enter) {
return 0;
}
//Continue through code
else {
//Loop to calculate unsigned magnitude
for (int i = 0; i < bitStore[i]; i++) {
unsignedMag = unsignedMag + (bitStore[i] * pow(NUMBER_TWO, i));
}
//Loop to calculate complete negation
for (int j = 0; j < bitStore; j++) {
negation[j] = ~bitStore[j]
}
negation = negation + 1;
for (int l = 0; l < negation; l++) {
twosComp = twosComp + (negation[l] * pow(NUMBER_TWO, l));
}
}
return 0;
}
【问题讨论】:
-
您可以通过
size_t size = sizeof(arr)/sizeof(arr[0])方法找到大小 - 但仅限于定义数组的位置,而不是传递的位置。
标签: c arrays twos-complement