【问题标题】:Return multiple values from scanf() without requiring 2 or more inputs? C language从 scanf() 返回多个值而不需要 2 个或更多输入? C语言
【发布时间】:2021-11-10 03:41:05
【问题描述】:

我目前在大学学习 C 语言课程。我总是喜欢把分配给我的作业编成用户友好且整洁的程序。所以,请记住,我是这方面的初学者。

虽然这是基本的,但我只需要帮助:

1    int count, sum, max, input;
2    count = 1;
3    sum = 0;
4    input = 0;
5    printf("This program will find the sum of your given 
6          input of an integer.\n");
7    printf("Please enter the number you would like the sum 
8          of: ");
9    scanf("%d", &max, &input);
10   while (count <= max){
11        sum = sum + count;
12        count++;
13    }
14    printf("The sum of %d is %d.\n", input, sum);
15    printf("==To exit the program, please enter anything, 
16          then press enter==");
17    scanf("%d");
18    return;
}

我想在第 14 行让用户知道他们首先输入的内容,同时也给他们输入的内容的总和。我该怎么做?

编辑:我知道第 9 行没有意义,但这就是我遇到问题的地方。我见过 scanf("%d%d", &var, &var);,但这需要用户有 2 个输入。我只想要1个输入。换句话说,如果用户输入一个数字,我希望只有 1 个输入同时进入 max 和 input。

编辑 2:例如,如果您输入要获得 10 的总和,我希望第 14 行显示您输入的输入以及 10 的总和。

【问题讨论】:

  • 发布示例输入和预期输出。
  • 如果只有一个输入,max和input是什么?是否将它们都设置为输入的单个值?
  • @chux-ReinstateMonica 我提供了一个带有编辑的示例。很抱歉。
  • @WilliamPursell 我遇到的问题是当我想要一个输入时,它没有正确显示。就像在我编辑的示例中一样,如果您输入 10,程序将显示The sum of 0 is 55。我想让 10 出现在位置 0 中,但我不知道如何在不需要 2 个输入的情况下做到这一点。编辑:所以我想你说的就是我的意思。我希望 max 和 input 都是输入的单个值。
  • @Barmar 好的,比如说用户输入10 作为输入变量。您要解释的是放置一个像input = max; 这样的函数语句,以便max 也具有10 的值,该值通过使用scanf(); 函数返回给input?

标签: c scanf


【解决方案1】:

我认为你不需要声明一个额外的变量“input”。(因为你的代码中 max 的值永远不会改变。)

只需检查以下代码:

1    int count, sum, max;  //removed input
2    count = 1;
3    sum = 0;
4                    //removed input
5    printf("This program will find the sum of your given 
6          input of an integer.\n");
7    printf("Please enter the number you would like the sum 
8          of: ");
9    scanf("%d", &max);
10   while (count <= max){
11        sum = sum + count;
12        count++;
13    }
14    printf("The sum of %d is %d.\n", max, sum); //replaced input by max
15    printf("==To exit the program, please enter anything, 
16          then press enter==");
17    scanf("%d");
18    return;
}

【讨论】:

    【解决方案2】:

    scanf() 只会分配给与格式字符串中的格式运算符一样多的变量。您提供的额外变量将被忽略,它不会获得相同输入值的副本。

    使用普通赋值将输入的值复制到第二个变量中。

    scanf("%d", &max);
    input = max;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多