2017-07-27 30 views
-7

我是初學者到c語言,我正在練習它來開發我的學習代碼。我正在嘗試使用if語句構建.c函數。如果條件爲真,我需要該函數做一些工作,如果沒有,則返回其他值。我來自R.我正在閱讀很多關於.c的教程,並且找不到對此問題的一些幫助。請幫忙嗎?如果在C語言中有雙值的語句?

注:我試圖做的是生成統一的數字,然後根據這些數字的值條件。

#include <stdio.h> 
int main() 
{ 
    double 0.5 ; 
    double *w; 
    for (i=0;i<= int 10; i++) w[i] = runif(0,1); 
    if (w[i] < double 0.5) 
    { 
     int 4 + int 5 
    } else if w[i] < double 0.2){ 
     int 10 + int 5 
    }else{ 
     w[i] 
    } 
    return 0; 
} 

我試過,但我得到這個錯誤:

expected identifier or '{' 
use of undeclared identifier 'w' 
+7

這裏有太多的錯誤,我不知道從哪裏開始。你應該閱讀一本關於C語言的好書。首先需要基礎知識......進一步'runif'在C中沒有可用的關鍵字或函數。這段代碼的目的是什麼? –

+1

你有沒有看過一些教程,讓你開始使用語法? – CodingLumis

+0

您需要先了解c語法 – MCG

回答

0

這裏和那裏都有很多語法錯誤。我在評論中解釋它。

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
//gets random doubles 
double fRand(double fMin, double fMax) 
{ 
    double f = (double)rand()/RAND_MAX; 
    return fMin + f * (fMax - fMin); 
} 
int main() 
{ 
    double j=0.5; 
    double *w; 

    //sets the random seed. 
    srand (time(NULL)); 

    //you must alloc memory to your pointer 
    w= new double[11]; 

    //you must declare i 
    //but you don't have to declare constant values such as 10 
    for (int i=0;i<=10; i++) 
    { 
     //use brackets to determine what is in your forloop 
     //you can potentially use indents but it is cleaner with brackets 

     // never used that function, you might as well check if it exists 
     //w[i] = runif(0,1); 
     //it seems to be the equivalent of rand() 
     w[i]=fRand(0,1); 
     if (w[i] < 0.5) 
     { 
      //what are you trying to do here? 
      //int 4 + int 5 
      //did you mean to do this? 
      w[i]=4+5; 
     } 
     else if(w[i] < 0.2)// you forgot your'(' here 
     { 
      //int 10 + int 5 
      w[i]=10+5; 
     } 
     //else no need for a else if you don't change the value of anything. 
     //{ 
     // w[i] 
     //} 
    } 
    return 0; 
} 
1

一些,但不是全部,在你的代碼中的錯誤如下所示:

你的第一雙沒有一個變量名,簡單加倍0.5 ;.你需要給它一個標識符,例如double my_double = 0.5 ;.

for循環的主體必須位於括號內。

for(bla bla) { 
    // code 
} 

你也需要給我一個類型,只是說我= 0是不夠的,你需要將其聲明爲INT I = 0,或雙I = 0.0或任何類型你喜歡。

你也忘了包裝你的其他 - 如果在括號中,並且你的條件也是無效的語法。您不需要將0.2聲明爲double,編譯器會自行推斷它。

}else if w[i] < double 0.2){ 

應該

}else if (w[i] < 0.2){ 

好像你肯定沒有認真努力學習C.

+0

他也嘗試訪問'w'作爲數組,但他沒有在堆或棧上分配空間那... –

+0

是的,我不知道他如何努力學習C,我從來沒有見過像這樣問過的問題。 –

+0

怎麼''(w [i] army007

2

我認爲,我們沒有人可以從代碼中推斷出你想要做什麼但是,這裏是一個編譯和正確的版本。現在,您可以調整它,讓它實現您真正想要做的事情。

#include <stdio.h> 
int main() 
{ 
    double w[11]; 
    int i, j; 
    for (i = 0; i <= 10; i++) { 
     w[i] = runif(0,1); 
     if (w[i] < 0.5) { 
     j= 4 + 5; 
     } else if (w[i] < 0.2) { 
     j= 10 + 5 ; 
     }else { 
     printf ("w[%d]= %f",i, w[i]); 
     } 
    } 
    return 0; 
} 
+0

這不會編譯,因爲'runif'不是標準的C函數,可以在GitHub上找到實現:https://github.com/atks/Rmath/blob/master/runif.c。但其餘的似乎很好! –

+1

@Andre,它會編譯。它會假設'runif'是extern,返回int,所以int被轉換爲double並被賦給'w [i]'。如果在任何庫或其他對象中找不到「runif」,它將不會鏈接。 –