在C中调用printf中的函数?

在C中调用printf中的函数?,c,C,我是C编程的初学者 我在写一个简单的程序来计算平均值 这是我的密码: #include <stdio.h> #include <stdlib.h> #include <conio.h> int main() { int n, s = 0, num, i; float avg; printf("Enter value of total no\n"); scanf("%d", &n); for (i=1; i<

我是C编程的初学者

我在写一个简单的程序来计算平均值

这是我的密码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
    int n, s = 0, num, i;
    float avg;
    printf("Enter value of total no\n");
    scanf("%d", &n);
    for (i=1; i<=n; i++)
    {
        void pri(int i){
            switch(i){
                case 1:
                    printf("st");
                    break;

                case 2:
                    printf("nd");
                    break;

                case 3:
                    printf("rd");
                    break;

                default:
                    printf("th");
                    break;
            }
        }
        printf("Enter %d pri(i) number\n", i);
        scanf("%d", &num);
        s += num;
    }
    avg = s / n;
    printf("The average is %f",avg);
    return 0;
}
但prii并没有像我预期的那样工作。但后来我找到了另一种方法,下面是代码的第二个版本:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
    int n, s = 0, num, i;
    float avg;
    printf("Enter value of total no\n");
    scanf("%d",&n);
    for (i=1; i<=n; i++)
    {
        void pri(int i){
            switch(i){
                case 1:
                    printf("enter 1st number\n");
                    break;

                case 2:
                    printf("enter 2nd number\n");
                    break;

                case 3:
                    printf("enter 3rd number\n");
                    break;

                default:
                    printf("enter %dth number\n",i);
                    break;
            }
        }
        pri(i);
        scanf("%d", &num);
        s += num;
    }
    avg = s / n;
    printf("the average is %f",avg);
    return 0;
}
我想从第一个版本获得第二段代码的结果


我可以调用PROTF中的函数,这些函数在程序中的某个地方被定义吗?

< p>您不能告诉Prtf在其执行过程中调用另一个函数。printf希望接收格式化字符串和参数,以替换该字符串的部分内容。由于多种原因,在格式化字符串中嵌入函数调用是不可能的

您可以做的是返回字符串而不是打印它并将其用作参数

const char *pri(int i) {
    switch(i) {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
    default:
        return "th";
    }
}

printf("enter %d%s number\n", i, pri(i));

C不支持在另一个函数中定义的嵌套函数。您的代码之所以能够工作,是因为编译器添加了对此类函数的支持作为扩展。一般来说,您应该避免嵌套函数。

不能在另一个函数的中间调用函数???我想这些年来我一直在编错程序;你真正的意思是不能在另一个函数中声明函数。@abelenky我的意思是调用。也许我可以更清楚地表达自己。我改了句子,太好了!注:需要为-21、-3、-2、-1、21、31、@OP的abelenky写道:printfenter%d优先级编号\n,i;希望printf在解释格式字符串时调用prii,并将结果字符串替换为格式字符串。你不能从字符串文本中调用函数,海报就是这么做的。您当然可以从另一个函数中调用函数。显然:printfoutput%s\n,GetOutputinput@mssirvi检查:这非常有用@山姆