c - 函数根本不返回值 - 不是 void

标签 c

我有一个不返回函数值的函数。我添加了一些随机测试人员来尝试和调试,但没有运气。谢谢!

#include <stdio.h>
#include <math.h>
#include <time.h>

#define N 100

float error(int a, int b); 

int main(){
    printf("START\n");

    srand(time(NULL)); 

    int a, b, j, m;
    float plot[N+1]; 

    printf("Lower bound for x: ");
    scanf("%d", &a);

    printf("Upper bound for x: ");
    scanf("%d", &b); 

    printf("okay\n");

    for(j = 0; j < N; j++)
        plot[j] = 0; 

    printf("okay1\n");

    m = error(a,b);
    printf("%f\n",m);

    return 0; 
}

float error(int a, int b){
    float product = a*b;
    printf("%f\n",product);
    return product; 
} 

所以无论如何,m = error(a,b) 总是给出 0!

请帮忙。我很抱歉没有清理这个......

最佳答案

这是因为您将 m 声明为 int。将其声明为 float 并将 a*b 转换为 float 因为 ab也是 int 。另一种方法是将函数的返回类型更改为 int ;

int error(int a, int b){
int product = a*b;
printf("%f\n",product);
return product; 
}    

并使用 %d 说明符打印 mproduct 。另外,不要忘记在后一种情况下更改函数原型(prototype)。

关于c - 函数根本不返回值 - 不是 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467307/

相关文章:

至少 375 次成功输入后出现代码段错误

c - 双链表-C

c - 难以打印字符指针数组

c++ - 准备要发布的公共(public) header

c - PaStreamCallbackTimeInfo成员全部为0

最接近的四点对c程序

C 中的组合求和

mysql - c语言与mysql(如何将mySQL数据库包含到程序中)

使用 C 中的二维数组和函数创建井字游戏程序

c - malloc 有效,cudaHostAlloc 段错误?