C循环增量

时间:2015-10-22 02:17:09

标签: c

如果为转换指定范围,我该如何进行增量?以下是代码:

    #include <stdio.h>

    int disrange(float x, float y);

    int main()
    {

        printf("The conversion from miles to km are:");
        printf("\n");
        printf("Miles  kilometers");
        printf("\n");

        // Set the range in Miles
        disrange(1,5,incr);  ---> extra params increment
 }    
    int disrange(float x, float y)
    {
       int a;

       for(a=x; a<=y; a++){
           // convert each value into km
           float b = a*1.61;        
           printf("%d   %f\n",a,b);
       }
    }

当增量为2时,打印输出应为1, 3, 5的转换。谢谢!

1 个答案:

答案 0 :(得分:3)

int disrange(float x, float y,float inc)
{
   int a;

   for(a=x; a<=y; a+=inc){
       // convert each value into km
       float b = a*1.61;        
       printf("%d   %f\n",a,b);
   }
}

如果您想要表格格式,请尝试:

int disrange(float x, float y,float inc)
{
   int a;

   for(a=x; a<=y; a+=inc){
       // convert each value into km
       float b = a*1.61;        
       printf("%6d\t%07.5f\n",a,b);
   }
}

这将使第一个字段的长度至少为6个字符,第二个字符为7个字符,小数点后为5个字符。有关printf

的更多信息,请参阅here