2017-07-27 69 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”,它将不会链接。 –