我无法理解我的C ++代码的输出 [英] I am unable to understand the output to my c++ code
问题描述
我在做一个问题,部分问题是将给定字符串n的给定字符串0和1移至给定数量(此处为sft变量)。 T查询。我在右移时遇到错误,而左移没有问题。整个代码如下-
I was doing a problem the part of the problem is to shift the a given string of 0 and 1 of a given number n to a given amount (here sft variable taken). T queries. I was getting error in right shift while left shift had no problem. The whole code is below -
#include<iostream>
#include<bitset>
using namespace std;
int main()
{
const int m=16;
int n,t;
cin>>t;
int sft;
char ch;
int arr[m];
while(t--)
{
cin>>n;
cin>>sft;
cin>>ch;
bitset<m>bt(n);
cout<<bt<<endl;
if(ch=='R')
{
for(int i=0;i<m;i++)
{
arr[i]=bt[((i+sft)%m)]; // problem is here
// cout<<((i+sft)%m)<<"-"<<bt[((i+sft)%m)]<<" "; // to check what is happening
}
}}}
问题-问题是,对于bt字符串中的给定位置,我没有得到应该得到的信息,但是给出的信息有误,我不知道为什么?
PROBLEM - The problem is that for a given position in bt string , I am not getting what I am supposed to get it is giving wrong bit I do not know why?
输入:
1(查询)
16(数字)3(平方英尺)R(右)
input :
1(queries)
16(number) 3 (sft) R(right)
输出
bt字符串= 0000000000010000
bt中的位置位= 3-0 4-1 5-0 6-0 7 -0 8-0 9-0 10-0 11-0 12-0 13-0 14-0 15-0 0-0 1-0 2-0
Output
bt string = 0000000000010000
Position-Bit in bt = 3-0 4-1 5-0 6-0 7-0 8-0 9-0 10-0 11-0 12-0 13-0 14-0 15-0 0-0 1-0 2-0
推荐答案
最低有效位为0,因此应在右侧,因此您的输出应为:
The least significant bit is 0, so that should be on the right side, so your output should be:
2-0 1-0 0-0 15-0 ... 5-0 4-1 3-0
2-0 1-0 0-0 15-0 ... 5-0 4-1 3-0
或0000000000000010(2),这是0000000000010000(16)的3个位置的右移
or 0000000000000010 (2) which is the right shift for 3 positions of 0000000000010000 (16)
因此,您可以进行循环右移(滚动)处理,但是输出
So your processing is okay for circular right shifting (rolling), but your output is confusing.
对于非圆形(逻辑)平移,请为无效位置引入0。
For non-circular (logical) shifting, introduce 0 for invalid positions.
另请参见: https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
这篇关于我无法理解我的C ++代码的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!