我试图在两个嵌套循环中填充数组但是对于每秒pPiece []我想分别给它一个0或1的k属性,每秒pPiece []
例如 -
pPieces[0] = new Piece(0,pcName,1);
pPieces[1] = new Piece(1,pcName,1);
pPieces[2] = new Piece(0,pcName,1);
pPieces[3] = new Piece(1,pcName,1);
etc....
我有什么
private Piece pPieces[] = new Piece[8];
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[j+k] = new Piece(k,pcName,1);
}
}
我认为这样做会导致pPieces []索引重写4次。是否可以正确地填充这个数组,该数组应该每秒存储8个对象&#39; k&#39;等于0或1?
答案 0 :(得分:2)
当前解决方案中的问题是j+k
在两个循环期间会多次获得相同的值:
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[j+k] = new Piece(k,pcName,1);
}
}
例如,当j = 0
和k = 1
时,您将拥有j + k = 1
。但是在j = 1
和k = 0
。
问题来自这样一个事实,即你应该将变量j
递增1步,此时应该按pcCount
的步长递增变量j
;相关问题是pCount*pcCount
应该转到pCount
而不是for(int j=0; j<pCount*pcCount; j+=pcCount) //<--- j+=pcCount here, not j++
{
for(int k=0; k<pcCount; k++)
{
String pcName = "Piece " + allocation();
pPieces[j+k] = new Piece(k,pcName,1);
}
}
。
pCount
作为附注,请考虑使用更具描述性的变量名称,而不是pcCount
和struct a2v {
float4 pos : POSITION;
float3 normal : NORMAL;
float2 texture : TEXCOORD0;
};
struct v2f {
float4 hpos : POSITION;
float2 texcoord : TEXCOORD0;
float4 col : COLOR0;
};
v2f main(a2v IN,
uniform float4x4 lightMatrix)
{
v2f OUT;
// convert texture coordinates to NDC position [-1, 1]
OUT.hpos.xy = IN.texture * 2 - 1;
OUT.hpos.z = 0.0;
OUT.hpos.w = 1.0;
// diffuse lighting
float3 N = normalize(mul((float3x3) lightMatrix, IN.normal));
float3 L = normalize(-mul(lightMatrix, IN.pos).xyz);
float diffuse = max(dot(N, L), 0);
OUT.col = diffuse;
OUT.texcoord = IN.texture;
return OUT;
}
。
答案 1 :(得分:2)
按如下方式重构您的代码,问题是pPieces[j+k] = new Piece(k,pcName,1);
Your j+k => 0,1,1,2,2,3,3,4
更正代码
private Piece pPieces[] = new Piece[8];
int count=0;
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[count++] = new Piece(k,pcName,1);
}
}
答案 2 :(得分:0)
实际上,j + k将重叠。但是2j + k没有。 您需要替换为:
私人作品pPieces [] =新作品[8];
for(int j=0; j<pCount; j++) //pCount = 4
{
for(int k=0; k<pcCount; k++) //pcCount = 2
{
String pcName = "Piece " + (allocation());
pPieces[2*j+k] = new Piece(k,pcName,1);
}
}
}
答案 3 :(得分:0)
%
运算符可以在这里使用:
private Piece pPieces[] = new Piece[8];
for(int j = 0; j < pPieces.length; j++) {
String pcName = "Piece " + (allocation());
pPieces[j] = new Piece(j % 2,pcName,1);
}
%
(模数)运算符返回整数除法的余数。
e.g。
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
创建1和0的交替。