C语言 如果数组中的元素为负,如何去掉逗号?

k4aesqcs  于 2022-12-11  发布在  其他
关注(0)|答案(2)|浏览(144)
for (int i = 1;  i <= size; i++)
{
    printf("Enter element %d: ", i);
    scanf("%d", &array[i]);
    if (array [i] < 0)
        break;
    
}
printf("[");
for (int i = 1; i <= size; i++)
{
    
    if (array[i] < 0)
        break;
    printf("%d", array[i]);
       
}
printf("]");

代码的输出如下

Enter size: 10
Enter element 1: 6
Enter element 2: 8
Enter element 3: 23
Enter element 4: -2
[6,8,23,]

教授希望是这样的

Enter size: 10
Enter element 1: 6
Enter element 2: 8
Enter element 3: 23
Enter element 4: -2
[6,8,23]
5n0oy7gb

5n0oy7gb1#

printf("[");
for (int i = 1; i <= size; i++)
{
    if (i != 1 && array[i] >= 0)
        printf(",");
    if (array[i] < 0)
        break;
    printf("%d", array[i]);
}
printf("]");
mnemlml8

mnemlml82#

任务不是删除逗号。任务是仅在需要时打印逗号。
有几种方法可以做到。这里有一种:

printf("[");
for (int i = 1; i <= size; i++)
{
    
    if (array[i] < 0)
        break;
    if (i == 1)
        printf("%d", array[i]);  // For index 1 don't print a comma
    else
        printf(",%d", array[i]); // For all others start with a comma
       
}
printf("]");

下面是另一个:

printf("[");
// Handle index one before the loop
if (size >= 1 && array[1] >= 0)
{
    printf("%d", array[1]);  // No comma printed
}
for (int i = 2; i <= size && array[i] >= 0; i++)
{
    printf(",%d", array[i]);  // Print comma before element
}
printf("]");

顺便说一句:数组索引通常从零开始,而不是从一开始

相关问题