Home > Blockchain >  How to remove the last comma on a number , and bug with decimals?
How to remove the last comma on a number , and bug with decimals?

Time:01-03

I wrote the code, I'm learning array, how can it not print my last comma on the numbers, and how does it load this decimal for me properly?

input n: 7
numbers: 7 1 0 2.1 -2 5 7 3
output: {-2,0,1,2,3,5,7,}
output which I need: {-2,0,1,2.1,3,5,7}

#include <stdio.h>

int main() {
    int i, j, a;
    float n;
    float num[100];
    printf("Input number n: \n");
    scanf("%f", &n);
    while (n < 1) {
        printf("Wrong input!\n");
        printf("Input numbers array: \n");
        scanf("%f", &n);
    }
    printf("Input %g number: \n", n);
    for (i = 0; i < n;   i)
        scanf("%f", &num[i]);
 
    for (i = 0; i < n;   i) {
        for (j = i   1; j < n;   j) {
            if (num[i] > num[j]) {
                a = num[i];
                num[i] = num[j];
                num[j] = a;
            }
        }
    }
    printf("\n{");
    for (i = 0; i < n;   i) {
        printf("%g,", num[i]);
    }
    printf("}");

    return 0;
}

CodePudding user response:

Method 1:

for (i = 0; i < n;   i)
        printf( "%g%s", num[i], i == n - 1 ? "" : "," );

Method 2:

for (i = 0; i < n - 1;   i) {
        printf( "%g,", num[i] );
}
printf("%g}", num[n - 1]);

Method 3: (after nielsen comment)

for (i = 0; i < n;   i)
        printf( i ? ",%g" : "%g", num[i] );

CodePudding user response:

In addition to the i486 answer and to solve the decimal part problem, you must be aware that by declaring

int a

whenever you do

a = num[i]

you are 'converting' num[i] to integer and therefore you lose the decimal part.

that's why it must be

float a
  •  Tags:  
  • c
  • Related