如何在c ++中使用提升功率 [英] how to use raise to the power in c++

查看:110
本文介绍了如何在c ++中使用提升功率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过此代码将二进制转换为十进制问题是如何使用2提升功率 -



i am trying to convert binary to decimal by this code the problem is that how to use 2 raise to the power -

#include<iostream>
using namespace std;
#include<conio.h>

int main()
{
	int a,b,temp=0,n;
	cout<<"Enter the range of natural no's : ";
	cin>>b;
	n==b;
	for(a=0;a<=n;a++)
	{
		temp=temp+n%10;
		temp=temp*2^a;
		n=n/10;
	}
	cout<<"\nThe sum of given natural no's is : "<<temp;
	getch();
	return 0;
}

推荐答案

让我们注意操作数是整数。找到2的整数幂 a 的最快方法是

Let's note that the operands are integers. The fastest way to find the integer power a of 2 is
int power = 1 << a;





Wes Aday在对该问题的评论中建议的方法仅适用于浮点计算;对于整数,它会涉及双重类型 - 不好。



请参阅: http://www.cprogramming.com/tutorial/bitwise_operators.html [ ^ ]。







但如果最终目标是计算二进制字符串表示,解决方案是不同的。 (只有不是十进制到二进制:你的整数值不能是十进制,只有字符串可以。你将二进制转换为二进制字符串,即提取字节)。



要查找二进制字符串,您需要提取每个字节并用0或1填充字符串。这是如何。首先,创建一个位掩码,它应该是2的幂,见上文。每个位都循环执行。对于每个位位置的掩码,您必须找到测试编号和掩码的逻辑AND。结果是零或不。如果为零,则文本位清零,否则设置为:



The method suggested by Wes Aday in his comment to the question is only good for floating point calculation; for integers it would involve double type cast — not good.

Please see: http://www.cprogramming.com/tutorial/bitwise_operators.html[^].



But if the ultimate goal is to calculate the binary string representation, the solution is different. (Only not "decimal to binary": your integer values cannot be "decimal", only strings can be. You convert binary to binary strings, that is, extract bytes).

To find binary string, you need to extract each byte and fill in the string with 0 or 1. Here is how. First, create a bit mask, which should be a power of 2, see above. Do it in cycle for each bit. For a mask for each bit position, you have to find logical AND of the test number and the mask. The result is either zero or not. If zero, the text bit is clear, otherwise it is set:

char bitDigit;
if ((1 << bit) & value) == 0)
    bitDigit = '0';
else
    bitDigit = '1';



根据位,在字符串中从左到右填充 bitDigit 的值位置,周期。



这就是全部。



-SA


除解决方案1外,还要注意以下问题:

In addition to Solution 1, watch the following problem:
n==b;



比较n和b并抛出结果!你可能想写:


Compares n and b and throws the result away! You probably meant to write:

n = b;


如果问题是,如何要打印某个整数值的内存映像,可以使用 bitset 。例如。
If the question is, how to print the memory image of some integer value, you might use bitset. E.g.
#include <bitset>
...
int x = ...
...
std::cout << "The binary value of x = " << x
          << " is " << std::bitset<sizeof(int)*8>(x)
          << std::endl;

另请参阅 http://www.cplusplus.com/reference / bitset / bitset / bitset / [ ^ ]。

干杯

Andi

See also http://www.cplusplus.com/reference/bitset/bitset/bitset/[^].
Cheers
Andi


这篇关于如何在c ++中使用提升功率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆