作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 printf 命令中打印函数参数。请大家帮忙推荐一下。
void printline(char ch, int len);
value(float, float, int);
main()
{
double amount;
printline('=', 30);
amount = value(500, 0.12, 5); // I want to print argument of function value. please help
printf("The total amount is: %f \n", amount);
//printf("%f\t%f\t%d\t%f \n", 500, 0.12, 5, amount);
printline('=', 30);
_getch();
}
void printline(char ch, int len)
{
int i;
for (i = 0; i < len; i++)
printf("%c", ch);
printf("\n");
}
value(float p, float r, int n)
{
int year;
float sum;
sum = p;
year = 1;
while (year <= 5)
{
sum = sum * (1 + r);
year = year + 1;
}
return(sum);
}
最佳答案
在您的 printline
函数中,您只有一个字符作为参数。所以迭代它是没有意义的。如果要打印字符串
或字符数组,则需要使用char *
或char[]
并对其进行迭代。所以你的函数 printline
可能如下所示:
void printline(char *ch, int len)
{
int i;
for (i = 0; i<len; i++)
printf("%c", ch[i]);
printf("\n");
}
只需确保 len
不大于 *ch
的长度即可。
更好的解决方案是,您不必担心 len
的值,而是逐个打印字符,直到遇到 \0
字符表示数组的结尾。
void printline(char *ch)
{
int i;
for (i = 0; ch[i] != '\0'; ++i)
printf("%c", ch[i]);
printf("\n");
}
If the string is null terminated, use
printf("%s", ch)
. If the string is not null terminated but the length is supplied, useprintf("%.*s", len, ch)
. In both cases, there's no loop in the user code; the loop is buried inside theprintf()
function. Further, since there's a newline printed after the loops, useprintf("%s\n", ch)
orprintf("%.*s\n", len, ch)
and skip the extraprintf()
after the loop.
关于c - 在C中: How to print function argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247075/
我是一名优秀的程序员,十分优秀!