创建函数重复字符

creating function repeat character

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

Enter a character and a number: A 7

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);
 
 } 

正在打印:

enter character and how many times repeated

a 4

ap ?U? * 13283362

我做错了什么?

第 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() and scanf() 的手册页,以了解这些函数的正确 sysntax。

有一个很基本的误解:

声明

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

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

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

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

你可以这样做:

#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);
}