【问题标题】:Writing a program to find the largest in a series of numbers.编写一个程序来找出一系列数字中最大的一个。
【发布时间】:2013-05-23 17:06:00
【问题描述】:

我对 C 非常陌生。我正在使用 King 第 2 版的现代 C 编程方法。

我被困在第 6 章。问题 1:编写一个程序,在用户输入的一系列数字中找到最大的数字。程序必须提示用户一一输入数字。当用户输入 0 或负数时,程序必须显示输入的最大非负数。

到目前为止我有:

#include <stdio.h>

int main(void)
{
float a, max, b; 

for (a == max; a != 0; a++) {
printf("Enter number:");
scanf("%f", &a);
}

printf("Largest non negative number: %f", max);

return 0;
}

我不明白问题的最后一部分,即如何在循环的用户输入结束时查看哪个非负数最大。

max = a > a ???

感谢您的帮助!

【问题讨论】:

  • 你希望for (a == max; a != 0; a++) 做什么?
  • 问题希望您在用户输入负数(或零)后立即停止并打印迄今为止输入的最大数字。顺便说一句,你的程序有问题,因为 max 没有初始化,并且在 for 循环中没有比较/重新分配 max。
  • Luchian,我在结尾部分标记为最大。
  • 然后测试 a 不等于 0。然后我想我可以尝试在最后的最大测试阶段将 a 增加到下一个字母?
  • @caelan:您的for 循环毫无意义。 a == max 部分将 amax (两者都未初始化)进行比较,并且在您拥有它的地方什么也不做 - for 的那部分用于执行初始化;你没有初始化任何东西。下一部分 a != 0 将导致未定义的行为,因为 a 未初始化 - 谁知道它拥有什么值?如果a 恰好是0,您的循环可能永远不会运行。

标签: c scanf


【解决方案1】:

因此,如果 a 大于循环中的每次迭代,您希望更新 max,如下所示:

#include <stdio.h>

int main(void)
{
    float max = 0, a;

    do{
        printf("Enter number:");

        /* the space in front of the %f causes scanf to skip
         * any whitespace. We check the return value to see
         * whether something was *actually* read before we
         * continue.
         */

        if(scanf(" %f", &a) == 1) {
            if(a > max){
                max = a;
            }
        }

        /* We could have combined the two if's above like this */
        /* if((scanf(" %f", &a) == 1) && (a > max)) {
         *     max = a;
         * }
         */
    }
    while(a > 0);

   printf("Largest non negative number: %f", max);

   return 0;
}

然后您只需在最后打印 max 即可。 do while 循环在这里是更好的选择,因为它至少需要运行一次。

【讨论】:

  • 愚蠢的代码小精灵。我已经删除了我的另一条评论。这是一项很好的工作,但您应该真正检查来自 scanf 的返回值,以确保实际上读取了某些内容。
  • @NikBougalis 可能应该检查一下,但这只是一个简单的问题。 TBH,我不太熟悉如何在 C 中处理错误。
  • 我调整了您的帖子以检查错误并正确跳过空格以及一些 cmets。希望这会有所帮助:)
  • 次要:建议将“a”初始化为0.0。如果不这样做,如果第一个 scanf 尝试读取垃圾,while (a>0) 将对未初始化的“a”进行操作。
【解决方案2】:
#include<stdio.h>

int main()
{
    float enter_num,proc=0;

    for(;;)
    {
       printf("Enter the number:");
       scanf("%f",&enter_num);


       if(enter_num == 0)
       {
           break;
       }

       if(enter_num < 0)
       {
           proc>enter_num;
           proc=enter_num;
       }

       if(proc < enter_num)
       {
           proc = enter_num;
       }

    }

    printf("Largest number from the above is:%.1f",proc);
    return 0;
}

【讨论】:

  • 在数字
猜你喜欢
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2023-02-07
  • 2020-07-08
  • 2022-12-20
  • 2020-02-21
  • 2022-12-18
相关资源
最近更新 更多