简体   繁体   English

C语言:函数中的float和void之间的区别

[英]C language: Difference between float and void in functions

I'm learning how to use the functions in C but I can't understand why while this: 我正在学习如何使用C中的函数,但是我不明白为什么这样做:

    float TableauDebut(float size[], float poi[], char sex[], int nbElem)
{
    int i;
    for(i=0; i < nbElem; i++){
    printf("  %d)%.2f  %.2f  ", i, size[i], poi[i]);
    switch(sex[i]){
        case 'F': printf("Woman\n"); break;
        case 'M': printf("Man\n"); break;
    }
}

displays my table as well as using void 显示我的表以及使用void

But when I try to do the same in Java: 但是,当我尝试在Java中执行相同操作时:

static void TableauDebut(double [] size, double [] poi, char [] sex, int nbElem)
{

    int i;
    for(i=0; i < nbElem; i++){
    System.out.printf("  %d)%.2f  %.2f  ", i, size[i], poi[i]);
    switch(sex[i]){
        case 'F': System.out.printf("Femme\n"); break;
        case 'M': System.out.printf("Homme\n"); break;
    }
}

I can just use void and not double 我只能使用void而不能加倍

What's the difference between using float and void in C language and why I cannot do the same in Java? 在C语言中使用float和void有什么区别?为什么我不能在Java中做同样的事情?

A void return type means your function doesn't return a value. 返回值类型void意味着您的函数不返回值。 Anything else means your function must return an object of that type (or, where applicable, something that is convertible to that type.) 其他任何事情都意味着您的函数必须返回该类型的对象(或在适用时返回可转换为该类型的对象)。

Your first example promises to return a float but fails to do so. 您的第一个示例承诺返回一个float但没有这样做。 This is an error, but a C compiler need not tell you about this. 这是一个错误,但是C编译器不需要告诉您这一点。 With suitable compiler settings you should get a warning, but the bottom line is that it is possible to compile such an erroneous piece of code in C, run it, and get undefined behaviour at runtime. 使用适当的编译器设置,您应该得到警告,但最重要的是,可以在C中编译这样的错误代码,然后运行它,并在运行时得到未定义的行为

Java protects you against this and fails to compile the code. Java可以防止这种情况,并且无法编译代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM