【问题标题】:Calling a Function Twice And Saving A Different Value Each Time两次调用函数并每次保存不同的值
【发布时间】:2021-12-31 16:27:37
【问题描述】:

我对 C 语言非常陌生,我正在编写的函数存在一些问题。任务是编写一个函数,在该函数中提示输入高度和宽度参数来绘制一个框。我编写了函数并且可以正确编译,但是我遇到的问题是我需要调用该函数两次并保存第一次调用的宽度和第二次调用的高度。现在,如果我可以使用传递引用,这将很容易,但我不允许这样做,因为函数必须是一个 int。这是我目前所拥有的。

//LaxScorupi
//11/21/2021
// C

 #include <cstdio>

int GetSize(int min, int max)
{
int range;

while (range < min || range > max)
{
    printf("Please enter a value between %d and %d: ", min, max);
    scanf("%d", &range);
}

return range;
}

/*
This is where I think I am missing something obvious. Currently, I 
have printf in place to 
just read the value back to me, but I know my "range" will be saved as 
whatever my second call
of GetSize is. I've tried creating variables for height and width, but 
am unsure how to take 
my return defined as range and store it as two different values. 
*/
 int main ()
{
int min;
int max;
int range;

range = GetSize(2, 80);
printf("Your width is %d\n", range;

range = GetSize(2, 21);
printf("Your height is %d\n", range);

return 0;
}

提前致谢 - Lax Scorupi

【问题讨论】:

  • 有什么问题?您无法将函数调用的结果保存在变量中吗?
  • 我的问题是当我调用该函数时,我只返回一个值,它被定义为范围。我想调用该函数两次,并将每次的输出都分配为可变的高度和宽度。最简单的方法是使用 pass-by-reference,但我不能用于此作业。
  • 请不要在问题中添加“已解决”。如果您找到了解决方案,请写下您自己问题的答案并将其标记为已接受。
  • 通过引用在这里对你没有帮助

标签: c linux unix


【解决方案1】:
struct
{
   int height;
   int width;
}range;

range.width = GetSize(2, 80);
range.height = GetSize(2, 21);

print("Height:%d, Width:%d\n", range.height, range.width);

【讨论】:

    【解决方案2】:

    基本上,您可以将它们保存在两个不同的变量中并将它们存储在一个数组中,以便您以后使用它们。我只是将名称和数组添加到您的代码中。

    #include<stdio.h>
    
    int GetSize(int min, int max)
    {
    int range;
    
    while (range < min || range > max)
    {
    printf("Please enter a value between %d and %d: ", min, max);
    scanf("%d", &range);
    }
    
    return range;
    }
    
    int main ()
    {
    int min;
    int max;
    int range1, range2;
    
    range1 = GetSize(2, 80);
    
    printf("Your width is %d\n", range1);
    
    range2 = GetSize(2, 21);
    printf("Your height is %d\n", range2);
    
    int a[2] = {range1, range2};
    printf("%d %d", a[0], a[1]);
    
    return 0;
    }
    

    【讨论】:

    • 请正确缩进代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    相关资源
    最近更新 更多