C 使用循环查找最大数
我正在写一个程序,在输入几个数字后,找出哪个数字最高C 使用循环查找最大数,c,loops,while-loop,max,C,Loops,While Loop,Max,我正在写一个程序,在输入几个数字后,找出哪个数字最高 #include <stdio.h> int main(void) { printf("...Find the highest number... (0 to exit)\n\n"); double num1; while (1) { printf("Enter a number: "); scanf("%lf", &num1); if (num
#include <stdio.h>
int main(void)
{
printf("...Find the highest number... (0 to exit)\n\n");
double num1;
while (1) {
printf("Enter a number: ");
scanf("%lf", &num1);
if (num1 == 0)
break;
}
return 0;
}
#包括
内部主(空)
{
printf(“…找到最大的数字…(0以退出)\n\n”);
双num1;
而(1){
printf(“输入一个数字:”);
扫描频率(“%lf”和num1);
如果(num1==0)
打破
}
返回0;
}
我该怎么做?我不知道怎么解决它。如果用户决定输入1000个数字fx,我不想创建1000个变量并存储每个数字。您可以添加一个变量来跟踪输入的最高值,例如,您可以在if station之后添加此变量
if (num1 > highest) {
highest = num1;
}
并将此添加到num1的声明中
double num1, highest = 0;
您需要声明两个变量。第一种类型,例如
int
,指示用户是否输入了至少一个不等于0.0的数字。第二个变量将存储当前最大的数字
这是一个演示程序
#include <stdio.h>
int main(void)
{
double largest;
printf( "...Find the highest number... (0 to exit)\n\n" );
int empty = 1;
while ( 1 )
{
double x;
printf( "Enter a number: " );
if ( scanf( "%lf", &x ) != 1 || x == 0.0 ) break;
if ( empty || largest < x )
{
empty = 0;
largest = x;
}
}
if ( !empty )
{
printf( "\nThe largest number is %.1f\n", largest );
}
else
{
puts( "\nYou have not entered any number unequal to 0" );
}
return 0;
}
定义两个变量,
currentNum
和max
。如果currentNum>max
重写max
值。只需跟踪最大值。您应该将highest
初始化为-DBL\u max
,除非只允许正值。@FiddlingBits哦,是的,我忘了这一点,添加thx的thx不是initialized@MickaelB. 你说得对!:)此外,如果用户键入的不是scanf将显示的数字,则可能需要添加错误处理stuck@MickaelB. 这不是我该做的。问题的作者可能会这样做。:)我刚刚演示了一种完成作业的方法。他是个初学者,既然你已经开始回答问题,你可以通过良好的实践来完成。
...Find the highest number... (0 to exit)
Enter a number: 3.3
Enter a number: 4.4
Enter a number: 1.1
Enter a number: 2.2
Enter a number: 9.9
Enter a number: 5.5
Enter a number: 0
The largest number is 9.9