gpt4 book ai didi

c++ - 霍纳斯定律需要代数帮助,显示错误答案 c++

转载 作者:搜寻专家 更新时间:2023-10-31 01:24:44 26 4
gpt4 key购买 nike

我希望在二进制数 11001101 中一次输入一个字符,然后输入一个 !并将其转换为十进制数。我将它乘以 2 并将其添加到前一项以给出我称为 decimal_num 的结果总数。

我在运行 while 循环时显示输出,数字从我期望的变为 98。我对调试语言的了解不够,因为这只是我第二次尝试写入它,任何信息都会有帮助。

int main() {

int base, decimal_num = 0;

char numberEnterInBase;

//Ask user for a base number:
cout << "Enter a base number from 2 and 10: " << endl << endl;

//Store input as base & check for correct input:
cin >> base;
while (base < 2 || base > 10) {
cout << "Please enter a number from 2 to 10." << endl;
cin >> base;
}

//Ask for a entry for number in base and store:
cout << "Please enter a number in that base terminated by !: " << endl;
cin >> numberEnterInBase;

//Subtract ASCII code for '0':
numberEnterInBase - '0';

//While loop to apply rules of Horners Law:
while (numberEnterInBase != '!') {

//Displays the numbers every pass through the loop to debug:
cout << "Numbers: Total: " << decimal_num << " , Char cin: " << numberEnterInBase << " , Base: " << base << endl;

/*
Taking char entered in and multiplying by base.
Then adds to total(decimal_num):
*/
decimal_num += numberEnterInBase * base;

//Displays the total after multiplying to help debug:
cout << decimal_num << endl << endl;

//Moves to next cin entry:
cin >> numberEnterInBase;
}

return 0;
}

-----OUTPUT-----

Enter a base number from 2 and 10:

2

Please enter a number in that base terminated by !:

1100101!

Numbers: Total: 0 , Char cin: 1 , Base: 2
98

Numbers: Total: 98 , Char cin: 1 , Base: 2
196

Numbers: Total: 196 , Char cin: 0 , Base: 2
292

Numbers: Total: 292 , Char cin: 0 , Base: 2
388

Numbers: Total: 388 , Char cin: 1 , Base: 2
486

Numbers: Total: 486 , Char cin: 0 , Base: 2
582

Numbers: Total: 582 , Char cin: 1 , Base: 2
680

Press any key to continue . . .

----EXPECTING----

I'm wanting 11001101  to equal 205.

Horner's Scheme:

((((((((1*2 + 1)2 + 0)2 + 0)2 + 1)2 + 1)2 + 0)2 + 1

1*2=2+1=3*2=6+0=6*2=12+0=12*2=24+1=25*2=50+1=51*2=102+0=102*2=204+1=205

11001101 (binary) = 205 (decimal)

最佳答案

numberEnterInBase - '0';

这是一个表达式。当从 numberEnterInBase 中减去 0 的 ASCII 代码时,它会评估您得到的结果,但随后该评估没有执行任何操作。它消失在以太中,就好像它从未存在过一样。

您可能打算用计算结果替换 numberEnterInBase 中的值。这可以通过以下两种方式之一完成。

选项 1:

 numberEnterInBase = numberEnterInBase - '0';

选项 2(更简洁):

 numberEnterInBase -= '0';

每次为 numberEnterInBase 获取新值时,您还需要重复此操作。

请注意,修复您的逻辑会弄乱您的调试输出,因为 numberEnterInBase 现在将包含一个控制字符(也称为“不可打印”字符)。您可以通过在流式传输时转换为整数来纠正这一点,例如(而不是完整的示例):

cout << static_cast<int>(numberEnterInBase);

此外,供将来引用:How to debug small programs . (它应该很有用,因为你的程序中还有另一个错误。)

关于c++ - 霍纳斯定律需要代数帮助,显示错误答案 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57750923/

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