-1

我有以下数组:

float a[]={ 1.123 12.123, 123.123, 12345.123};

如何创建以下输出(裁剪小数部分):

1.123
12.12
123.1
12345
4

5 回答 5

2
float a[]={ 1.123, 12.123, 123.123, 12345.123};
for(int i = 0 ; i < 4 ; i++) {
    int digits = 4 - log10(a[i]);
    digits = digits < 0 ? 0 : digits;
    digits = digits > 3 ? 3 : digits;
    printf("%.*f\n",digits,a[i]);
}
于 2013-01-18T08:22:28.963 回答
1
int main()
{  
  float a[]={ 1.123, 12.123, 123.123, 12345.123}; 

  for(int i=0; i<4; i++)
  {
    std::stringstream ss;
    ss << a[i];
    std::string s;
    ss >> s;
    s.resize(5);        // it only works with 99999
    cout << s << "\n";
  }
  cout << endl; 

  return 0;
}
于 2013-01-18T08:03:26.033 回答
1
#include <stdio.h>
#include <string.h>

int main(int argc,char* argv[]){

    float a[]= { 1.123, 12.123, 123.123, 12345.123};

    int i;
    char floatString[100] = {0};

    for (i=0; i < sizeof(a)/sizeof(a[0]); i++) {
        memset(floatString, 0, sizeof(floatString));
        sprintf(floatString, "%f", a[i]);
        floatString[5] = '\0';
        printf("%s\n", floatString);
    }
    return 0;
}
于 2013-01-18T07:31:46.867 回答
1

你可以用这个,

printf("%1.3f\n%2.2f\n%3.1f\n%5.0f\n", a[0], a[1], a[2], a[3]);
于 2013-01-18T08:49:51.653 回答
0

你可以snprintf这样使用:

int main()
{
    float a[]= { 1.123, 12.123, 123.123, 12345.123 };
    char buf[8];
    int i;
    for (i=0;i<sizeof(a)/sizeof(a[0]);i++) {
        snprintf(buf, 6, "%f", a[i]);
        printf("%s\n",buf);
    }
}
于 2013-01-18T09:05:27.583 回答