【问题标题】:How can I filter out a value above 100 so that it doesn't puts it in the sum如何过滤掉大于 100 的值,使其不计入总和
【发布时间】:2019-09-28 15:15:26
【问题描述】:

程序要求输入速度,当速度高于 100 时,不应将该值包括在平均速度的计算中。我该怎么做?

我放了一个 i--;在 else if 它说 else if(speed > 100) 的地方。它会重复问题,但不会删除大于 100 的值。

#include <stdio.h>

int main(){

    int i;
    double speed, sum = 0.0;
    float average; 

    for( i = 0; i < 10; i ++ ){ // asks 10 times the printf
        printf("%d Enter speed: ", i);
        scanf("%lf",&speed); // saves the input speed

        sum += speed; // sum = sum + speed; 

        // decides which gear to use
        if (speed == 0){
            printf("gear N\n");
        }else if (speed < 0 ){
            printf("gear R\n");
        }else if(speed <= 10.0){
            printf("gear 1\n");
        }else if (speed <= 30.0){
            printf("gear 2\n");
        }else if (speed <= 60.0){
            printf("gear 3\n");
        }else if (speed <= 80.0){
            printf("gear 4\n");
        }else if (speed <= 100.0){
            printf("gear 5\n");
        }elseif (speed > 100 ){ // when input higher than 100 dont save the input and ask again
            printf("max speed 100 km/h\n");
             i--;  
        }else 
            printf("Error!\n");
    }

    average = sum/i; // average calculation

    printf("average speed = %.2lf km/h", average); // prints out the average

    return(0);
}

当我输入 200 时,它应该删除该值并再次询问。当我输入 200 时,它会再次询问,但会使用 200 来计算平均值。

【问题讨论】:

  • C# 语言标签有什么用?该代码显然不是 C#,所以我为您删除了它。请不要使用不相关的标签发送垃圾邮件。另外请花一些时间阅读how to ask good questionsthis question checklist
  • 至于你的问题,我建议你花点时间学习如何调试你的代码。对于这种情况,一个好的开始是一些简单的rubber duck debugging,并密切注意你做事的顺序。或者使用调试器逐条执行代码,同时监控变量及其值。
  • 只需从sum 中减去speed
  • @csabinho 我要在哪里减去它
  • 在这种情况下,除了从sum 中减去speed,您还可以将sum += speed 移动到大if 块下方,并在减少索引@987654332 后添加continue @。 -- 这表明您只想在速度得到验证时添加。

标签: c for-loop if-statement


【解决方案1】:

也许这可以起作用:

elseif (speed > 100 ){ // when input higher than 100 dont save the input and ask again
            printf("max speed 100 km/h\n");
            sum-=speed;
             i--;  
        }

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多