【问题标题】:What should my function include to return the value of -1.0 if the wrong input is given?如果输入错误,我的函数应该包括什么来返回 -1.0 的值?
【发布时间】:2020-02-06 04:01:06
【问题描述】:

这是项目说明:

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

我认为我的大部分程序都是正确的,除了我在功能部分有困难。我们还没有学习 if else 语句,所以我不能使用这些语句。我的想法是有条件的 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");


    }

}

【问题讨论】:

  • while (y &lt;= 0); 要么是无限循环,要么根本没有循环...您的函数打印不返回任何内容,并且不应该循环根本
  • 我明白了,功能不完整。我只是列出我所拥有的和我的想法以供澄清。
  • 我会做return y&lt;=0 ? -1.0 : y;
  • "调用时,你的函数会返回第一个参数除以第二个参数。" 所以从基本功能入手,然后修改函数处理边缘案例。但是向用户报告错误的工作不属于该功能。它通过return -1.0; 通知调用者。不过,这是一项设计不佳的任务:似乎没有限制提供否定参数,例如1.0-1.0
  • 如果调用者试图除以 0,我需要该函数来划分用户输入并返回 -1.0 的值。

标签: c visual-studio function call return-value


【解决方案1】:

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

  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.html
http://man7.org/linux/man-pages/man3/scanf.3.html

【讨论】:

  • 感谢您的回复。但是我不能使用 if else 语句,因为我们还没有在课程中介绍它们。
  • 非常感谢您抽出宝贵的时间,我会投票,但我目前还没有达到这样做的水平。
猜你喜欢
  • 1970-01-01
  • 2011-01-14
  • 2019-09-18
  • 2021-01-18
  • 2014-05-31
  • 2015-11-17
  • 2019-09-09
  • 2012-09-03
  • 2021-01-05
相关资源
最近更新 更多