【问题标题】:Printing integers passed as arguments in function in C打印在C函数中作为参数传递的整数
【发布时间】:2016-02-23 03:53:11
【问题描述】:

我对 C 编程非常陌生,并且在编译应该非常简单的函数时遇到了麻烦。该函数名为 printSummary,只需将 3 个整数作为参数,然后打印一些文本以及这些整数。例如,如果 hits=1、misses=2 和 evictions=3,则 printSummary(hits,misses,evictions) 应打印以下内容:

命中:1 未命中:2 驱逐:3

这是我正在使用的代码。提前感谢您的任何建议。

#include<stdio.h>

void printSummary(int hits, int misses, int evictions)
{
    printf('hits: %d\n');
    printf('misses: %d\n');
    printf('evictions: %d\n');
}

int main()
{
    int hit_count = 1;
    int miss_count = 2;
    int eviction_count = 3;
    printSummary(hit_count, miss_count, eviction_count);
    return 0;
}

编译这段代码给了我几个警告,但没有错误。当我运行代码时,出现分段错误。就像我说的,我对 C 相当陌生,所以很可能有一个我只是缺少的简单解决方案。提前感谢您的任何建议。

【问题讨论】:

  • 第 1 步 'hits: %d\n' --> "hits: %d\n" " vs '
  • 请始终列出您收到的警告和错误。 “给我几个警告”是件好事,但除非你告诉我们你收到了哪些警告,否则最终没用。
  • 将 ' 更改为 " 有效。它们的工作方式不同有什么原因吗?
  • 'a' 在 C 中是字符文字的表示法,而 "abc" 是字符串文字。

标签: c integer printf


【解决方案1】:

您的 printf 函数没有被正确调用。您必须包含打印所需的整数:

printf("hits: %d\n", hits);
printf("misses: %d\n", misses);
printf("evictions: %d\n", evictions);

阅读有关 printf 函数的更多信息here。

【讨论】:

  • 我之前尝试过,但仍然收到一堆警告。执行您的建议并将 ' 更改为 " 似乎有效。' 和 " 有不同的含义吗?
  • 刚刚向我解释过,' 用于字符,而 " 用于 C 中的字符串
  • 啊,我现在明白了...我需要将 ' 更改为 "。我已经编辑了我的答案。
【解决方案2】:

错误是:

void printSummary(int hits, int misses, int evictions)
{
    /* Name: printf
    Prototype: int printf (const char *template, ...)
    Description:
    The printf function prints the optional arguments under the
     control of the template string template to the stream stdout. 
    It returns the number of characters printed,or a negative value if
     there was an output error.*/

    printf("hits: %d\n", hits); // don't use ' it is used only for char variable for example: char a = 'c';
    printf("misses: %d\n", misses);
    printf("evictions: %d\n", evictions);
}

【讨论】:

    【解决方案3】:

    进行以下更改。

       printf("hits: %d\n",hits);
       printf("misses: %d\n",misses);
       printf("evictions: %d\n",evictions);
    

    printf 有一个

    int printf(const char *format, ...)
    

    原型。因此,在第一个参数中,您可以传递格式说明符,然后在下一个参数中提供要打印的实际变量/值

    【讨论】:

    • 您介意解释一下 OP 做错了什么,以便他能够理解和学习吗?
    • 我曾认为使用 %d 只是习惯于已经按顺序给出参数。没有意识到我必须指定它们。
    猜你喜欢
    • 1970-01-01
    • 2016-04-30
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    相关资源
    最近更新 更多