gpt4 book ai didi

C语言: Write a program that would take 30 integers and prints the largest number and the smallest number

转载 作者:行者123 更新时间:2023-11-30 20:48:25 25 4
gpt4 key购买 nike

编写一个程序,接受 5 个整数并打印最大数字和最小数字

我尝试了这段代码

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num1, num2, num3, num4, num5;
int largest;
int smallest;

printf ( "\nEnter five integers." );
printf ( "\nAnd I will give you the smallest and the largest." );

scanf( "%d%d%d%d%d", &num1, &num2, &num3, &num4, &num5 );

if ( num1 >= num2, num3, num4, num5 )
{
( "num1 = largest" );
}

if ( num1 <= num2, num3, num4, num5 )
{
( "num1 = smallest" );
}

if ( num2 >= num1, num3, num4, num5 )
{
( "num2 = largest" );
}

if ( num2 <= num1, num3, num4, num5 )
{
( "num2 = smallest" );
}

if ( num3 >= num1, num2, num4, num5 )
{
( "num3 = largest" );
}

if ( num3 <= num1, num2, num4, num5 )
{
( "num3 = smallest" );
}

if ( num4 >= num1, num2, num3, num5 )
{
( "num4 = largest" );
}

if ( num4 <= num1, num2, num3, num5 )
{
( "num4 = smallest" );
}

if ( num5 >= num1, num2, num3, num4 )
{
( "num5 = largest" );
}

if ( num5 <= num1, num2, num3, num4 )
{
( "num5 = smallest" );
}

printf ( "The largest integer is %d.", largest);
printf ( "The smallest integer is %d.", smallest);

return 0;
}

但是出了点问题!

请问谁能帮忙解决一下这个问题吗?如果我们可以用 while 循环来做到这一点,请解释一下

谢谢

最佳答案

if ( num1 >= num2, num3, num4, num5 )

这不是比较多个项目的方式。这是有效的 C 代码,但逗号运算符从左到右执行每段代码,并且语句的结果是最后一段的结果。所以你的代码基本上变成:

if (num5)

这不是你想要的。这是比较多个项目的方法:

if ( num1 >= num2 && num1 >= num3 && num1 >= num4 && num1 >= num5 )

另外,

( "num4 = largest" );

确实什么也没做。我想你的意思是

largest = num4;

解决此问题的更可靠方法是首先询问用户他们想要比较多少个数字。这并不限制您只有 5 或 30 个输入。然后,您可以使用 for 循环获取输入,并进行比较:

// How many numbers the user wants to input
int numInput = 0;
printf("How many numbers to compare? ");
scanf(" %d", &numInput);

// Initialize
int largest = INT_MIN;
int smallest = INT_MAX;

int input;

// Loop
for (int i = 0; i < numInput; i++) {
// Get next number
printf("Enter #: ");
scanf(" %d", &input)) {
// Compare
if (input > largest) largest = input;
if (input < smallest) smallest = input;
}
// Print results
printf("Largest: %d, smallest: %d\r\n", largest, smallest);

注意,需要错误检查。例如:您应该检查 scanf 的返回值以确保您获得了一个数字。

关于C语言: Write a program that would take 30 integers and prints the largest number and the smallest number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40725868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com