如果输入错误,我的函数应包括什么以返回-1.0的值?

问题描述 投票:-1回答:1

这里是项目说明:

“编写一个包含名为doublemaster的double类型的函数的C程序,它接受两个double参数(您必须编写divmaster函数)。调用时,您的函数将返回第一个参数除以第二个参数。确保您的函数包括决策语句,以使其不能被0除-如果调用者尝试将其除以0,则该函数应返回-1.0值。您的程序应调用divmaster,然后显示该函数返回的值。然后使用参数22和3提交输出。请记住,结构化函数应该只有一个return语句。“

我认为我的大多数程序都正确,除了我在功能部分上遇到困难。我们还没有学习if语句,所以我不能使用它们。我的想法是有条件的while语句,如果输入0,则返回值-1.0。任何想法将不胜感激。

这里是我到目前为止的代码。

#include <stdio.h>
double divmaster(double x, double y);

int main(void)
{
    double i, j, value;

    printf("Please enter two numbers ");
    printf("the first number will be divded by the second. The value ");
    printf("will then be returned. Enter q to quit\n");

    while (scanf("%d%d", &i, &j) == 2)
    {
        value = divmaster(i, j);
        printf("%d divded by %d is %.6f\n", i, j, value);
        printf("Please enter the next paid of numbers or q to quit.\n");
    }

    return 0;
}

    double divmaster(double x, double y)
    {

        while (y <= 0);
        printf("-1.0");


    }

}
c visual-studio function call return-value
1个回答
0
投票

您的代码有几个主要问题:

  1. scanfprintf的字符串格式是错误的,%d格式为int,并且您将double作为参数,double的正确格式是%lf
  2. 您应该在每种格式之间使用分隔符。
  3. 您的函数divmaster缺少return语句。

这是修复代码后的样子。

#include <stdio.h>
double divmaster(double x, double y);

int main(void)
{
    double i, j, value;

    printf("Please enter two numbers ");
    printf("the first number will be divded by the second. The value ");
    printf("will then be returned. Enter q to quit\n");

    while (scanf("%lf %lf", &i, &j) == 2)
    {
        value = divmaster(i, j);
        printf("%lf divded by %lf is %.6lf\n", i, j, value);
        printf("Please enter the next pair of numbers or q to quit.\n");
    }

    return 0;
}

double divmaster(double x, double y)
{

    if (0.0f == y)
        return -1.0f;
    else
        return x / y;
}

如果无法使用if else语句,则也可以使用while语句

while (0.0f == y)
    return -1.0f;

return x/y;

每种类型的正确格式都在手册中为这些功能中的每一个定义了http://man7.org/linux/man-pages/man3/printf.3.htmlhttp://man7.org/linux/man-pages/man3/scanf.3.html

© www.soinside.com 2019 - 2024. All rights reserved.