在 C 中使用 printf 打印空格数 [英] print number of spaces using printf in C

查看:188
本文介绍了在 C 中使用 printf 打印空格数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我该怎么做,在 C 中使用 printf 打印一定数量的空格我在想这样的事情,但我的代码在第一个 printf 语句之后也没有打印,我的程序编译得非常好.我猜我必须打印 N-1 个空格,但我不太确定该怎么做所以.

I was wondering how can I do it ,to print certain number of spaces using printf in C I was thinking something like this,but also my code doesn't print after the first printf statement,my program compiles perfectly fine tho.I'm guessing I have to print N-1 spaces but I'm not quite sure how to do so.

谢谢.

#include <stdio.h>
#include <limits.h>
#include <math.h>

int f(int);

int main(void){
    int i, t, funval,tempL,tempH;
    int a;

    // Make sure to change low and high when testing your program
    int low=-3, high=11;
    for (t=low; t<=high;t++){
        printf("f(%2d)=%3d\n",t,f(t));                 
    }
    printf("\n");
    if(low <0){
        tempL = low;
        tempL *=-1;
        char nums[low+high+1];
        for(a=low; a <sizeof(nums)/sizeof(int);a+5){
            printf("%d",a);
        }
    }
    else{
        char nums[low+high];
        for(a=low; a <sizeof(nums)/sizeof(int);a+5){
            printf("%d",a);
        }
    }

    // Your code here...
    return 0;
}


int f(int t){
    // example 1
    return (t*t-4*t+5);

    // example 2
    // return (-t*t+4*t-1);

    // example 3
    // return (sin(t)*10);

    // example 4
    // if (t>0)
    //  return t*2;
    // else
    //  return t*8;
}

输出应该是这样的:

   1       6       11      16      21      26     31
   |       |       |       |       |       |       |  

推荐答案

打印 n 个空格

printf 有一个很酷的宽度说明符格式,可以让你传递一个 int 来指定宽度.如果空格数 n 大于零:

Printing n spaces

printf has a cool width specifier format that lets you pass an int to specify the width. If the number of spaces, n, is greater than zero:

printf("%*c", n, ' ');

应该可以解决问题.我也想到你可以对大于或等于零的 n 这样做:

should do the trick. It also occurs to me you could do this for n greater than or equal to zero with:

printf("%*s", n, "");

打印 1, 6, 11, ... 图案

我仍然不完全清楚您想要什么,但要生成您在帖子底部描述的确切模式,您可以这样做:

Printing 1, 6, 11, ... pattern

It's still not fully clear to me what you want, but to generate the exact pattern you described at the bottom of your post, you could do this:

for (i=1; i<=31; i+=5)
    printf("%3d   ", i);
printf("\n");
for (i=1; i<=31; i+=5)
    printf("  |   ");
printf("\n");

输出:

  1     6    11    16    21    26    31   
  |     |     |     |     |     |     |   

这篇关于在 C 中使用 printf 打印空格数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆