Return 来自 scanf() 的多个值而不需要 2 个或更多输入? C语言

Return multiple values from scanf() without requiring 2 or more inputs? C language

我目前在大学学习C语言class。我总是喜欢让布置给我的作业变得用户友好且整洁。所以,请记住,我是初学者。

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

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 个输入同时进入 maxinput

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

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

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

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

我认为您不需要声明一个额外的变量“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;
}