我想要每次填充 64 个整数时进行确认打印. ? 如何检查 i == 64


#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 intsn", j, 512 / 64);
}
}
printf("filling completedn");
return 0;
}

但是程序控件永远不会进入 for 循环中的if语句。 我想在每次填充 64 个整数时都得到一个 print 语句。

谢谢。

这是一个简单的运算符优先级错误。==&更强的结合力。 你需要写:

if((i&0x7f) == 64)

另请注意,这可能不是您想要的,因为它在i为 64+n*128 时打印;

您可以简单地使用:

if(i%64 == 0)

如注释中所述,如果要打印64ints写入buf,则应将条件更改为:

if(i%64 == 63)

因为i等于0,你已经写了一个元素。

测试不正确。它应该是:

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 intsn", j, 512 / 64);
}
}
printf("filling completedn");
free(buff);
return 0;
}

这是一个更紧凑的版本。你不需要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 intsn", (i / 64) + 1, 512 / 64);
}
}
printf("filling completedn");
return EXIT_SUCCESS;
}

最新更新