You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过循环校验并更新upper_bound输入值:解决上下界输入异常

Fixing Upper Bound Validation in Your Input Function

Hey there! Let's sort out that input validation issue you're facing. The core problem in your current code is that you're comparing pointer addresses instead of the actual numeric values the user entered—since upper_bound and lower_bound are pointers to double variables. Here's how to fix it:

The Key Mistake

Your original code uses upper_bound < lower_bound in the condition checks. This compares the memory locations of the pointers, not the values stored at those locations. To access the actual input values, you need to dereference the pointers with the * operator.

Corrected Code

void inputs(double *coefficient_a, double *coefficient_b, double *coefficient_c, double *lower_bound, double *upper_bound, int *number_of_steps) {
    printf("Enter coefficient A -> ");
    scanf("%lf", coefficient_a);
    printf("Enter coefficient B -> ");
    scanf("%lf", coefficient_b);
    printf("Enter coefficient C -> ");
    scanf("%lf", coefficient_c);
    printf("Enter lower bound -> ");
    scanf("%lf", lower_bound);
    printf("Enter upper bound -> ");
    scanf("%lf", upper_bound);

    // Validate upper bound against lower bound (using dereferenced values)
    while (*upper_bound < *lower_bound) {
        printf("\nError: upper bound must be greater than lower bound!");
        printf("\nEnter upper bound -> ");
        scanf("%lf", upper_bound);
    }

    printf("Enter number of steps for trapezoidal sum -> ");
    scanf("%i", number_of_steps);
    return;
}

What Changed & Why

  • Dereferenced pointers: We replaced upper_bound < lower_bound with *upper_bound < *lower_bound. This tells the program to compare the actual numeric values the user input, not the memory addresses of the pointers.
  • Simplified loop: Switched from a do-while to a while loop. This avoids an unnecessary "Enter upper bound" prompt when the user enters a valid value on the first try—only triggering the re-input prompt if the validation fails.

Now, whenever the user enters an upper bound smaller than the lower bound, the loop will keep asking for a new value until a valid one is provided, and that new value will automatically overwrite the original (since we're writing directly to the pointer's target address with scanf("%lf", upper_bound)).

内容的提问来源于stack exchange,提问作者GMAn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:56:19