【问题标题】:creating function repeat character创建函数重复字符
【发布时间】:2015-06-20 02:37:15
【问题描述】:

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

输入一个字符和一个数字: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);
 
 } 

正在打印:

输入字符和重复次数

一个4

ap ?U? * 13283362

我做错了什么?

【问题讨论】:

  • printf("%s*%d", &c);

标签: c loops char printf scanf


【解决方案1】:

第 1 点:您需要更改代码

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

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

在您的代码中,ccharchar 的正确格式说明符是 %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() 的手册页以了解这些函数的正确语法。

【讨论】:

  • @CoolGuy 谢谢。添加了整个\t 本身。 :-)
  • \t 可能不是 OP 所追求的:“A A A A”
  • @Jongware 非常抱歉。不知何故错过了那部分。相应更新。感谢您指出这一点并避免进一步混淆。
【解决方案2】:

你可以这样做:

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

【讨论】:

  • 请修正您的格式,"%c"-> "%c "(用一个空格分隔字符),您的 while() 应该是 for() 或更好地替换为 while(num--)
【解决方案3】:

有一个非常基本的误解:

声明

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

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

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

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

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 2014-04-05
    • 2016-12-25
    • 2014-10-24
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    相关资源
    最近更新 更多