我正在编写一个程序,假设输入以无符号大小和二进制补码给出,将给定的位串(最多 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;
}
最佳答案
"Is there a way to get the array to go through the loop without the array size being known?"
没有。数组大小在声明数组且大小已知时是固定的:例如@Observer
size_t size = sizeof bitStore/sizeof bitStore[0];
相反,由于代码具有“给定的位串(最多 32 位)”,因此将数组定义为大小 32(或者 33 是一个 string 是理想的)。
跟踪分配了多少数组。
//int bitStore[n];
int bitStore[MAX_BITS];
int count = 0;
// char bit = getchar();
int bit = getchar(); // Use `int` to account for potentially 257 different values
//while (getchar != enter) {
while (count < MAX_BITS && (bit == '0' || bit == '1')) {
bit = bit - '0';
// Do not read again, instead save result.
//scanf("%c", &bitStore[bit]);
bitStore[count++] = bit;
// getchar();
bit = getchar();
}
to not use the pow and multiplication functions.
通过移位简单地加或乘以 2。目前尚不清楚为什么 OP 的目标是不使用“乘法”。我看不出有什么理由禁止 *
。当底层乘法开销很大时,一个好的编译器会生成高效的代码,因为 *2
很难优化。
// int unsignedMag;
unsigned unsignedMag = 0; // initialize
// for (int i = 0; i < bitStore[i]; i++) {
for (int i = 0; i < count; i++) {
// preferred code, yet OP wants to avoid * for unclear reasons
// unsignedMag = unsignedMag*2 + bitStore[i];
unsignedMag = unsignedMag + unsignedMag + bitStore[i];
}
pow()
在这里出于很多原因最好避免。最重要的是,对整数问题使用 double
数学会遇到宽整数的精度问题。
converts a given bit string (up to 32-bits) into decimal
请注意,此任务不需要 bitStore[]
数组。只需在读取数据时形成 unsignedMag
。
关于c - 在 C 编程中声明一个没有 Size 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52468564/