简体   繁体   English

C 程序运行一个额外的循环

[英]C program running an extra loop

Write a program that points to the table of values of a given function.编写一个程序,指向给定 function 的值表。 The initial value of x changes with step d, until the value of y (which is function of x) become greater than a number c x 的初始值随着步骤 d 变化,直到 y 的值(即 x 的 function)变得大于一个数字 c

I have been trying to solve this task for some time but I always come across the same problem.我一直试图解决这个任务一段时间,但我总是遇到同样的问题。 The program always throws me one more value.该程序总是给我带来更多价值。 See code.见代码。 Thanks in advance.提前致谢。

#include <stdio.h>
#include <math.h>

main(){
    float x,d,y=0;
    float c;
    printf("Write begin and end of interval: ");
    scanf("%f%f",&x,&c);
    printf("Write step d: ");
    scanf("%f",&d);
    printf("x         y\n");
    while (c>y){
        y=pow(x,2)+(1/sqrt(x+1));
        printf("%.2f   %.2f\n",x,y);
        x+=d;
    }
}

This is what program does这就是程序所做的

Write begin and end of interval: 1 5
Write step d: 0.5
x         y
1.00   1.71
1.50   2.88
2.00   4.58
2.50   6.78  -------> this is undesired because y>c

Mathematical expression数学表达式

在此处输入图像描述

Just add an if statement that checks for y after calculation.只需添加一个if语句,在计算后检查 y。 Note that you have to change it to c<=y if you don't want y=c to also not get printed.请注意,如果您不希望y=c也不被打印,则必须将其更改为c<=y

#include <stdio.h>
#include <math.h>
int main(){
    float x,d,y=0;
    float c;
    printf("Write begin and end of interval: ");
    scanf("%f%f",&x,&c);
    printf("Write step d: ");
    scanf("%f",&d);
    printf("x         y\n");
    while (c>y){
        y=pow(x,2)+(1/sqrt(x+1));
        if(c<y){
            break;
        }
        printf("%.2f   %.2f\n",x,y);
        x+=d;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM