It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have been reading a programming book and it wants me to write a program listing a table of the first 10 factorial numbers. I have been trying for the past 45 minutes, but can't come up with a solution. Please Help! I'm pretty sure the program involves using loops.
The easiest way to calculate the factorial is with a recursive function or a simple loop as shown below. I'll leave it up to you to figure out how to list the information in a table as there are lots of ways to skin that cat.
Header File Function Declaration:
-(int)factorialRecursive:(int)operand;
-(int)factorialLoop:(int)operand;
Implementation File Function Declaration:
-(int)factorialRecursive:(int)operand
{
if( operand == 1 || operand == 0) {
return(1);
} else if( operand < 0 ) {
return(-1);
}
return( operand * [self factorialRecursive:operand-1] );
}
-(int)factorialLoop:(int)operand
{
if( operand == 1 || operand == 0) {
return(1);
} else if( operand < 0 ) {
return(-1);
}
int factorial = 1;
for(int i = operand; i > 1; i-- ) {
factorial *= i;
}
return( factorial );
}
Sample Call:
int factNumber = 10;
NSLog(#"%d! = %d",factNumber,[self factorialRecursive:factNumber]);
NSLog(#"%d! = %d",factNumber,[self factorialLoop:factNumber]);
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Maybe I'm too tired, but when adding the following Log.d in the code (now commented out) the , Studio shows a compile error on the last "else if" (where (formId == 98))... Please advise
formViewModel?.questionGeneralData?.id?.let { formId ->
if (formId == 10 && !interactor.getIsRetroactive()) {
interactor.setCaffeineCounter(answer.toString())
// Log.d("5732", "455ryhrdhgbfhbdrfhbg")
} else if (formId == 14) {
if (answer == 0) {
if (BuildConfig.FLAVOR == BOOST_FLAVOR) {
interactor.addSkippedForm(15, FormEnums.FormType.MORNING_FORM)
} else {
interactor.addSkippedForm(15, FormEnums.FormType.MORNING_FORM_REFRESH)
}
} else {
interactor.removeSkippedForm(15)
}
} else if (formId == 97 && !interactor.getIsRetroactive()) {
HomeSharedPrefs.put(SleepApp.getInstance().applicationContext, caffeineTaken, answer)
} else if (formId == 98 && !interactor.getIsRetroactive()) {
HomeSharedPrefs.put(SleepApp.getInstance().applicationContext, alcoholTaken, answer)
}
}
I would say that when you do that, the return type of that first if statement is different than all the other statements. Since the let function (https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/let.html) expects a type for the return value that might be causing this compilation issue.
Use .also instead OR return same data-type from all if-else branches.
Also, put that log statement above interactor.setCaffeineCounter(answer.toString()).
Based on Joao Dias answer, the solution is to switch places the Log.d with the line before it (put it after the Log.d), so first the Log is executed, and then the line after it runs, and returns the value, that the let expects
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I'm getting Expected expression errors on the following code:
(void) for(t; t < kPlatformsStartTag + kNumPlatforms; t++) { //error here
CCSprite *platform = (CCSprite*)[batchNode getChildByTag:t];
CGSize platform_size = platform.contentSize;
CGPoint platform_pos = platform.position;
max_x = platform_pos.x - platform_size.width/2 - 10;
min_x = platform_pos.x + platform_size.width/2 + 10;
float min_y = platform_pos.y + (platform_size.height+bird_size.height)/2 - kPlatformTopPadding;
if(bird_pos.x > max_x &&
bird_pos.x < min_x &&
bird_pos.y > platform_pos.y &&
bird_pos.y < min_y) {
[self jump];
}
}
(void) for(t; t < kCloudsStartTag + kNumClouds; t++) { //error here
CCSprite *cloud = (CCSprite*)[batchNode getChildByTag:t];
CGPoint pos = cloud.position;
pos.y -= delta * cloud.scaleY * 0.8f;
if(pos.y < -cloud.contentSize.height/2) {
currentCloudTag = t;
[self resetCloud];
} else {
cloud.position = pos;
}
}
The error is found where the "for" code is. I put the (void) code in because I will get an Expression result unused error. Any ideas?
The (void) before the for loop does not make sense.
You have to remove the (void) before the for loop because it's not a valid c syntax. You can't solve an error with another error.
You may ask the question : Why puting (void) before the for loop prevented the unused expression error. Well that's because the debugger didn't reach it. and it doesn't know for what is for as he expected a resulted value from it to cast it to void.
When the compiler is generating the error: Unused Entity Issue - Expression result unused. That's means that your program is evaluating an expression without using it.
In your case at the for loop if the t variable is already initialized as you want it, you shouldn't put it at the first part as it will be considired as an unused expression.
for(; t < kPlatformsStartTag + kNumPlatforms; t++) { // keep the first expresion empty
// ...
}
You've already got answers about the bogus (void), but not about the unused expression.
for(t; t < kCloudsStartTag + kNumClouds; t++)
The initial expression here, t, has absolutely no effect, and for that reason has no business being present at all. The value of t is read and immediately discarded, and any decent compiler will optimise that by not even bothering to read t. You do not need an expression here. You can remove it, and write
for(; t < kCloudsStartTag + kNumClouds; t++)
although personally, I might be tempted to go with a while loop instead.
Edit: reading your code more closely, your code seems to need to give t an initial value.
for(t = 0; t < kCloudsStartTag + kNumClouds; t++)
Either way, your attempt to suppress the warning without understanding what the warning was telling you wasn't a good idea.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am new to TLM.
Someone can give me an example code for connecting two processes by a TLM fifo?
Thank you
I searched in doulos, but I only saw examples of sockets.
Someone helped me and I leave here a code example of a tlm fifo
#include "systemc"
#include "tlm.h"
// PRODUCER 1
SC_MODULE(producer)
{
sc_core::sc_port< tlm::tlm_fifo_put_if<int> > out; //FIFO OUT
SC_CTOR(producer)
: out("out")
{
SC_THREAD(run); //função
}
void run()
{
int i = 42;
std::cout << name() << ": " << i << std::endl;
out->put(i);
}
}; // producer
// CONSUMER
SC_MODULE(consumer)
{
sc_core::sc_port< tlm::tlm_fifo_get_if<int> > in;
SC_CTOR(consumer)
: in("in")
{
SC_THREAD(run); //função
}
void run()
{
int i = in->get();
std::cout << name() << ": " << i << std::endl;
}
}; // consumer
// MAIN
int sc_main(int, char*[] )
{
tlm::tlm_fifo<int> fifo("fifo");
producer prod("producer");
prod.out(fifo);
consumer cons("consumer");
cons.in(fifo);
sc_core::sc_start();
char myLine[100];
cin.getline(myLine, 100);
return 0;
}
Thank you
there are some good examples in doulos website.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
Please see the formulæ below.
It's the solution to a circle chord problem where A is the arc length and C is the chord length.
I want to find the Radius r.
The formula below uses factorials and powers etc which I don't know how to express in Objective C.
Can somebody help by converting the formula into Objective C language?
a = A² – C²
b = -2A^4/4!
c = 2A^6/6!
d = -2A^8/8!
//Let:
f = c/a-b²/3a²
g = d/a+2b³/27a³-bc/3a²
x = cuberoot(-g/2 + sqrt(g²/4+f³/27)) – cuberoot(g/2 + sqrt(g²/4+f³/27)) - b/3a
r = sqrt(x)
This should work:
double factorial(int x)
{
double result = 1;
for (x = x; x > 0; x--)
{
result *= x;
}
return result;
}
...
int A = 20;
int C = 25;
double a = A*A - C*C;
double b = -2.0*pow(A, 4.0)/factorial(4);
double c = 2.0*pow(A, 6.0)/factorial(6);
double d = -2.0*pow(A, 8.0)/factorial(8);
//Let:
double f = c/a-(b*b)/(3.0*(a*a));
double g = d/a + 2.0*pow(b, 3.0)/(27.0*pow(a, 3.0))-(b*c)/(3.0*a*a);
double x = pow(-g/2.0 + sqrt(g*g/4.0+pow(f, 3.0)/27.0), 1.0/3.0) - pow(g/2.0 + sqrt(g*g/4.0+pow(f, 3.0)/27.0), 1.0/3.0) - b/(3.0*a);
double r = sqrt(x);
The header is <math.h>. You square by multiplying a factor by itself; you cube by multiplying a factor by itself twice. The factorials are constants; you precalculate them, or let the computer do so:
enum { factorial_3 = 1 * 2 * 3 }; // Not needed, but an example
enum { factorial_3 = 3 * factorial_2 }; // Alternative technique
The function sqrt() gives you the square root. If it is available, then cbrt() from C99 gives you a cube root. When it isn't available, you can use pow() instead. If the notation A^4, A^6 and A^8 is equivalent to A4, A6, A8, then those are easily handled as multiplications.
You can assemble the bits and pieces using this information.
For exponents, you can use math.h(which you'll need to import)'s pow(float base, float exponent) function. Then for factorials, you'll have to create one yourself. The following function should work (I didn't try it out yet).
long factorial(int number)
{
long numb = 1;
for (int i=1;i<=number;i++)
{
numb*=i;
}
return numb;
}
However, be aware that it's very easy to get too huge numbers with factorials, so use long long (or even malloc if necessary) if you need to get the factorial of a large number.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
In need some help with this little programming .. I just got 3 errors ..
:'(
**[
#include <stdio.h>
int main (void)
{
char A , B , C , D , E , F;
float id1[]; <<< *Definition of variable with array type needs an explicit size or an initializer*
float grade[]; <<< *Definition of variable with array type needs an explicit size or an initializer*
float marks[]; <<< *Definition of variable with array type needs an explicit size or an initializer*
float average;
float num1, kk=0;
/********* Jami, Abdulrahman *********/
printf("Enter The Student ID: ");
scanf("%d", &num1);
for (kk=0; kk<num1; kk++);
{
scanf("%d", &id1[kk]);
scanf("%d", &grade[kk]);
}
for (kk=0; kk<num1; kk++);
{
if (grade [kk]>85 &grade [kk]<=100);
A=A+1;
if (grade [kk]>70 &grade [kk]<85);
B=B+1;
if (grade [kk]>55 &grade [kk]<70);
C=C+1;
if (grade [kk]>40 &grade [kk]<55);
D=D+1;
if (grade [kk]>25 &grade [kk]<40);
E=E+1;
if (grade [kk]>=0 &grade [kk]<25);
F=F+1;
}
/********* Jami, Abdulrahman *********/
float aveerage;
float avrg, sum, lk;
sum = sum + marks[lk];
average = sum / num1;
for (lk=0; lk<num1; lk++);
return average;
}
]**
You must give it a size like 3 (it can be any integer though) or something:
For example:
float id1[];
//Should be:
float id1[3]; //Or whatever number you want.
Or you can do:
float id1[] = { 0, 0, 0 }; //To get the same effect as id1[3] where they would all be initialized at zero.
Or even better:
float id1[3] = { }; //Initialize all 3 elements to zero.
The error tells you that you need to set a size on these arrays. Try defining them as float myArray[maxMarks];
Of course maxMarks is the maximal number of marks, not the highest mark...
Try something like
float *id1;
or
float id1[100];
or
float id1[] = { 1.0, 2.0, 3.3, 7.2, 9.1, 1.5, 4.1 };
The [] can only be empty if you initialize the array with values. if you use float *id1;, you'll have to malloc() memory to use it. The other two are real arrays.
As other said: read the error messages you get and think about what they could mean.