我嘗試制作一個程式,它將在數字之間的某個位置放置一個逗號。我的解釋可能含糊不清,但我只是想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(",");}
}
}
}
這個程式不起作用,我不知道為什么。我希望你們能幫助我。非常感謝!
uj5u.com熱心網友回復:
#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, '\0'); // Don't have decimal separator
}
mod = (p - m) % 3; // Comma must be placed on each mod count
p = m; // Rewind the pointer
while (*p != '\0') // 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
uj5u.com熱心網友回復:
其實是我無意中拿到的。這是新代碼
#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.34或12345678.87。
uj5u.com熱心網友回復:
請您嘗試以下操作:
#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;
}
它可以帶或不帶小數位。此外,逗號的位置是自動計算的。您不必顯式分配它們。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/361325.html
上一篇:我怎么能溢位記憶體
