#include <stdio.h>
int main() {
int i;
int *buff;
int j = 0;
buff = malloc(sizeof(int) * 512);
for (i = 0; i < 512; i++) {
buff[i] = i;
if (i & 0x7f == 64) {
j++;
printf("completed %d part out of total %d parts ints\n", j, 512 / 64);
}
}
printf("filling completed\n");
return 0;
}但是程序控制从来没有进入for循环中的if语句。我想在每次填充64个整数时得到一条print语句。
谢谢。
发布于 2019-01-21 01:43:06
这是一个简单的运算符优先错误。==比&绑定得更强。你需要写下:
if((i&0x7f) == 64)还要注意,这可能不是您想要的结果,因为它在i为64+n*128时打印;
您可以简单地使用:
if(i%64 == 0)正如注释中指出的,如果要在64 ints写入buf时打印,则应将条件更改为:
if(i%64 == 63)因为当i等于0时,您已经在中编写了一个元素。
发布于 2019-01-21 01:41:31
测试不正确。它应该是:
if ((i & 0x3f) == 0x3f) {但是请注意,它将更具可读性,如下所示
if (i % 64 == 63) {修复其他小问题:
#include <stdio.h>
#include <stdlib.h>
int main() {
int i, j;
int *buff = malloc(sizeof(int) * 512);
if (buff == NULL)
return 1;
for (i = j = 0; i < 512; i++) {
buff[i] = i;
if (i % 64 == 63) {
j++;
printf("completed part %d out of total %d parts ints\n", j, 512 / 64);
}
}
printf("filling completed\n");
free(buff);
return 0;
}发布于 2019-01-21 02:12:48
这是一个更紧凑的版本。你不需要j。
#include <stdio.h>
int main()
{
int *buff = malloc(sizeof(int) * 512);
for (int i = 0; i < 512; i++)
{
buff[i] = i;
if (i % 64 == 63)
{
printf("completed %d part out of total %d parts ints\n", (i / 64) + 1, 512 / 64);
}
}
printf("filling completed\n");
return EXIT_SUCCESS;
}https://stackoverflow.com/questions/54279133
复制相似问题