Question

In: Computer Science

Here is my fibonacci code using pthreads. When I run the code, I am asked for...

Here is my fibonacci code using pthreads. When I run the code, I am asked for a number; however, when I enter in a number, I get my error message of "invalid character." ALSO, if I enter "55" as a number, my code automatically terminates to 0. I copied my code below. PLEASE HELP WITH THE ERROR!!!

#include
#include
#include
#include
#include

int shared_data[10000];

void *fibonacci_thread(void* params);
void parent(int* numbers);

int main() {

   int numbers = 0; //user input.

   pthread_t child; // create thread
   pthread_attr_t attr;
   pthread_attr_init(&attr);

   parent(&numbers); // get user input then start separate thread.
   pthread_create(&child, &attr, fibonacci_thread, (void*) &numbers); //starts fibonacci thread
   pthread_join(child, NULL); //waits for thread to finish

   //output to command prompt after thread finishes.
   for(int i = 0; i <= shared_data[i]; i++) {
       printf("%d",shared_data[i]);
   }

   return 0;
}

void *fibonacci_thread(void* params) {

   int fib0 = 0, fib1 = 1, next = 0;
   int *pointer;
   pointer = (int*) params;
   int total = *pointer;

   for (int i = 0 ; i < total; i++ ) {
if ( i <= 1 )
next = i;
else {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
}
   next = shared_data[i]; //store to shared_data array
   }
   //pthread_exit(0);
   return NULL;
}

void parent(int* numbers) {
   std::cout<<"Enter in a number to generate the Fibonacci sequence: ";
   std::cin>>*numbers;

   while(isdigit(*numbers) != true) {
       std::cout<<"Invalid character, please enter in a number: ";
       std::cin>>*numbers;
   }

   return;
}

here is the error below:

student@tuffix-vm:~$ cd CPSC-351-Project2-Fall2020
student@tuffix-vm:~/CPSC-351-Project2-Fall2020$ g++ -pthread fibonacci.cpp -o fibonacci
student@tuffix-vm:~/CPSC-351-Project2-Fall2020$ ./fibonacci
Enter in a number to generate the Fibonacci sequence: 2
Invalid character, please enter in a number: 3
Invalid character, please enter in a number: 4
Invalid character, please enter in a number: 5
Invalid character, please enter in a number: 6
Invalid character, please enter in a number: 7
Invalid character, please enter in a number: 8
Invalid character, please enter in a number: 9
Invalid character, please enter in a number: 55
student@tuffix-vm:~/CPSC-351-Project2-Fall2020$


Solutions

Expert Solution

Please look at my code and in case of indentation issues check the screenshots.

--------------main.cpp---------------

#include <pthread.h>
#include <iostream>
#include <stdlib.h>
#include <string>

int shared_data[10000];

void *fibonacci_thread(void *params);
void parent(int *numbers);
bool isNumber(std::string str);

int main()
{
   int numbers = 0;   //user input.

   pthread_t child;   // create thread
   pthread_attr_t attr;
   pthread_attr_init(&attr);

   parent(&numbers);   // get user input then start separate thread.
   pthread_create(&child, &attr, fibonacci_thread, (void*) &numbers);   //starts fibonacci thread
   pthread_join(child, NULL);   //waits for thread to finish

   //output to command prompt after thread finishes.
   for (int i = 0; i < numbers; i++)
   {
       printf("%d ", shared_data[i]);   //prints the array written by the thread
   }
   std::cout << "\n";
   return 0;
}

void *fibonacci_thread(void *params)
{

   int fib0 = 0, fib1 = 1, next = 0;
   int *pointer;
   pointer = (int*) params;
   int total = *pointer;

   for (int i = 0; i < total; i++)   //loop to generate next fibonacci number
   {
       if (i <= 1)
           next = i;
       else
       {
           next = fib0 + fib1;
           fib0 = fib1;
           fib1 = next;
       }
       shared_data[i] = next;   //store to shared_data array
   }
   //pthread_exit(0);
   return NULL;
}

void parent(int *numbers)
{
   std::string input;
   std::cout << "Enter in a number to generate the Fibonacci sequence: ";
   std::cin >> input;       //read the input as a string

   while (isNumber(input) != true)   //check if input is a number
   {
       std::cout << "Invalid input, please enter in a number: ";
       std::cin >> input;           //if not a number ask for another input
   }
   *numbers = atoi(input.c_str());   //if input was a number, convert it from string to integer

   return;
}

bool isNumber(std::string str)   //this function takes a string and checks if it is a positive number
{
   for (int i = 0; i < str.length(); i++)
   {
       if (!isdigit(str[i]))   //is digit is used to check if one character is a digit
           return false;   //when even one character is not a digit, return false
   }
   return true;   //if all characters are digits return true
}

----------Screenshots--------------

----------Output--------------

----------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs down.
Please Do comment if you need any clarification.
I will surely help you.

Thankyou


Related Solutions

Below is my source code for file merging. when i run the code my merged file...
Below is my source code for file merging. when i run the code my merged file is blank and it never shows merging complete prompt. i dont see any errors or why my code would be causing this. i saved both files with male names and female names in the same location my source code is in as a rtf #include #include #include using namespace std; int main() { ifstream inFile1; ifstream inFile2; ofstream outFile1; int mClientNumber, fClientNumber; string mClientName;...
Python I am creating a class in python. Here is my code below: import csv import...
Python I am creating a class in python. Here is my code below: import csv import json population = list() with open('PopChange.csv', 'r') as p: reader = csv.reader(p) next(reader) for line in reader: population.append(obj.POP(line)) population.append(obj.POP(line)) class POP: """ Extract the data """ def __init__(self, line): self.data = line # get elements self.id = self.data[0].strip() self.geography = self.data[1].strip() self.targetGeoId = self.data[2].strip() self.targetGeoId2 = self.data[3].strip() self.popApr1 = self.data[4].strip() self.popJul1 = self.data[5].strip() self.changePop = self.data[6].strip() The problem is, I get an error saying:  ...
Please look at the following code. When I run it from the command line, I am...
Please look at the following code. When I run it from the command line, I am supposed to get the following results: 1: I am 1: I am I need to fix it so that the functions 'print_i' and 'print_j' print all of their lines. What do I need to add? Thank you. C source code: #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> // These two functions will run concurrently void* print_i(void *ptr) { printf("1: I am...
How would I make it so that when I run my code it does not ask...
How would I make it so that when I run my code it does not ask for input (not having to enter after the statement and enter 0 for example) after ROXY (Forever ROXY Enterprises) appears? Like it would tell me the second statement right away along with the Roxy phrase. This is in C++. My code: #include / #include using std::endl; int main() {    void readAndConvert();    unsigned int stockSymbol;    unsigned int confNum;    std::cout << "ROXY...
I am trying to do edge detection using matlab. I have posted code here. It does...
I am trying to do edge detection using matlab. I have posted code here. It does not give any error but it's not running it at all. So please help me to fix it and also exaplin each line of this code pls. Thanks! i = imread('C:\Users\Amanda\Desktop"); I = rgb2gray(1i); BW1 = edge(I,'prewitt'); BW2= edge(I,'sobel'); BW3= edge(I,'roberts'); subplot (2,2,1); imshow(I); title('original'); subplot(2,2,2); imshow(BW1); title('Prewitt'); subplot(2,2,3); imshow(BW2); title('Sobel'); subplot(2,2,4); imshow(BW3); title('Roberts');
My code does not compile, I am using vim on terminal and got several compiling errors...
My code does not compile, I am using vim on terminal and got several compiling errors this is C++ language I need help fixing my code below is the example expected run and my code. Example run (User inputs are highlighted): Enter your monthly salary: 5000 Enter number of months you worked in the past year: 10 Enter the cost of the car: 36000 Enter number of cars you’ve sold in the past year: 30 Enter number of misconducts observed...
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
I'm getting an error with my code on my EvenDemo class. I am supposed to have...
I'm getting an error with my code on my EvenDemo class. I am supposed to have two classes, Event and Event Demo. Below is my code.  What is a better way for me to write this? //******************************************************** // Event Class code //******************************************************** package java1; import java.util.Scanner; public class Event {    public final static double lowerPricePerGuest = 32.00;    public final static double higherPricePerGuest = 35.00;    public final static int cutOffValue = 50;    public boolean largeEvent;    private String...
Below is my code in C#, When I run it, the output shows System.32[], Can you...
Below is my code in C#, When I run it, the output shows System.32[], Can you please check and let me know what is the problem in the code. class Program { static void Main(string[] args) { int number=12; Console.WriteLine(FizzArray(number)); } public static int[] FizzArray(int number) { int[] array = new int[number]; for (int i = 1; i < number; i++) array[i] = i; return array; }
This is for my finance class and I am a bit stuck. We're asked to use...
This is for my finance class and I am a bit stuck. We're asked to use the Delta hedging formula (i.e. how much stock to hold) for the multiperiod binomial model to confirm that a financial derivative paying the stock price at time t=N (i.e. V_N = S_N) must be priced with V_0 = S_0 today.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT