使用for循环在数字中插入逗号不起作用

Inserting commas in numbers using for loop not working

我尝试制作一个程序,它会在数字之间的特定位置放置一个逗号。我的解释可能比较含糊,我就是想把12345678.23变成12,345,678.23。我希望这清除了我的解释。这是我的代码。

#include<stdio.h>
#include<string.h>

void main()
{
  char m[20]="12345678.23";
    int j=11, a, t=1, r=4, s;
    
    
        for(a=0; a=11; a++)
        {
            if(strlen(m)==j)
            {printf("%c", m[a]);
            if(a==t)
            {printf(",");}
            if(a==r)
            {printf(",");}
            }   
        }
        
    
}

这个程序不工作,我不知道为什么。我希望你们能帮助我。非常感谢!

#include <stdio.h>
#include <string.h>

int main(void) // Use the proper signature
{
    char m[] = "123"; // Do not hardcode the size
    char *p; // A pointer to traverse the string
    int mod; // Useful to know when to insert a comma

    p = strchr(m, '.'); // Position of the decimal separator
    if (p == NULL)
    {
        p = strchr(m, '[=10=]'); // Don't have decimal separator
    }
    mod = (p - m) % 3; // Comma must be placed on each mod count
    p = m; // Rewind the pointer
    while (*p != '[=10=]') // While the character is not NUL
    {
        if (*p == '.') // Decimal separator reached
        {
            mod = 3; // Avoid divisibility
        }
        // If position divisbile by 3 but not the first pos
        if ((p != m) && (mod != 3) && (((p - m) % 3) == mod))
        {
            putchar(',');
        }
        putchar(*p);
        p++; // Next character
    }
    putchar('\n');
    return 0;    
}

输出:

12,345,678.23

其实我是无意中得到的。这是新代码

#include<stdio.h>
#include<string.h>

void main()
{
char m[12];
gets(m);
int j, a, t=1, r=4;
for(j=11; j>=0; j--)
    { 
        for(a=0; a<=j; a++)
        {
            if(strlen(m)==j)
            {
                printf("%c", m[a]);
                if(a==t)
                {
                printf(",");
                }
                if(a==r)
                {
                printf(",");
                }
            }   
        }
        t--;
        r--;
    }
}

输入的末尾至少要保留 2 位小数,例如 1234.3412345678.87

请您尝试以下操作:

#include<stdio.h>
#include<string.h>

int main()
{
    char m[]="12345678.23";
    int len = strlen(m);                // length of string "m"
    char *p = strchr(m, '.');           // pointer to the decimal point
    int dp;                             // length of the decimal position (including the dot)

    if (p == NULL) dp = 0;              // decimal point does not appear
    else dp = len - (int)(p - m);       // length of the decimal position

    for (int i = 0; i < len; i++) {     // loop over the characters of "m"
        putchar(m[i]);                  // print the character at first
        if ((len - dp - i - 1) % 3 == 0 && i < len - dp - 1) putchar(',');
                                        // print the comma every three digits from the 1's place backward
    }
    putchar('\n');

    return 0;
}

无论有没有小数位,它都适用。此外,逗号的位置是自动计算的。您不必明确分配它们。