Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

C program running an extra loop

Write a program that points to the table of values ??of a given 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

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
");
    while (c>y){
        y=pow(x,2)+(1/sqrt(x+1));
        printf("%.2f   %.2f
",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

enter image description here

question from:https://stackoverflow.com/questions/65875447/c-program-running-an-extra-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just add an if statement that checks for y after calculation. Note that you have to change it to c<=y if you don't want y=c to also not get printed.

#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
");
    while (c>y){
        y=pow(x,2)+(1/sqrt(x+1));
        if(c<y){
            break;
        }
        printf("%.2f   %.2f
",x,y);
        x+=d;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...