簡體   English   中英

C 程序運行一個額外的循環

[英]C program running an extra loop

編寫一個程序,指向給定 function 的值表。 x 的初始值隨着步驟 d 變化,直到 y 的值(即 x 的 function)變得大於一個數字 c

我一直試圖解決這個任務一段時間,但我總是遇到同樣的問題。 該程序總是給我帶來更多價值。 見代碼。 提前致謝。

#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;
    }
}

這就是程序所做的

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

數學表達式

在此處輸入圖像描述

只需添加一個if語句,在計算后檢查 y。 請注意,如果您不希望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