创建函数重复字符

时间:2015-04-14 13:04:54

标签: c loops char printf scanf

编写一个程序,提示用户输入字符和整数。实现一个名为repeat_character()的函数,它接受用户输入的两个参数(字符和整数),并通过在字符之间用单个空格复制整数次来显示字符。例如:

  

输入字符和数字:A 7

     

A A A A A A A A

这是我的代码:

int num;
char c;

void repeat_character(char,int);
int main() {
     printf("Enter character and how many times repeated\n");
     scanf("%s%d",&c,&num);

    repeat_character(c,num);
    return 0;

}  

 void repeat_character(char c, int num) 
{
     if (num>=1)
     printf("%s*%d", &c);
     else
         printf(0);

 } 

正在打印:

  

输入字符和重复次数

     

a 4

     

ap?U? * 13283362

我做错了什么?

3 个答案:

答案 0 :(得分:2)

第1点:您需要更改代码

scanf("%s%d",&c,&num);

scanf(" %c%d",&c,&num);
代码c中的

charchar的正确格式说明符是%c,而不是%s

第2点:您已在repeat_character()中使用loop。提供给printf()格式字符串不是评估,正如您可能预期的那样。你需要做一些像

这样的事情
void repeat_character(char c, int num) 
{
     int counter = 0;
     for (counter = 0; counter < num; counter ++)
         printf("%c ", c);     //notice the change in format specifier
 }

注意:我建议您在执行任何其他操作之前阅读printf()scanf()的手册页,以了解这些函数的正确sysntax。

答案 1 :(得分:1)

有一个非常基本的误解:

声明

printf("%s*%d", ...);

将打印两个参数,以*字符分隔:A*7它将打印该字符7次。

如果要多次打印字符,请使用循环:

while(num--) printf("%c ", c);

答案 2 :(得分:0)

你可以这样做:

#include<stdio.h>

int num;
char c;

void repeat_character(char, int);

int main() {
printf("Enter character and how many times repeated\n");
scanf("%c%d", &c, &num);        //getting inputs corresponding

repeat_character(c, num);       //calling function and sending parameters
getch();
return 0;

}

void repeat_character(char c, int num)     //receiving parameters
{
if (num >= 1){              //checking if number is greater than zero
    int i = num;            //initializing i with num
    while (i != 0){         //loop will continue till it value becomes zero
        printf("%c", c);    //printing char single time in each iteration 
        i--;                //decrementing the value of i
    }
}
else
    printf(0);
}