Need some help with the problem.
When I compile my code below, it gives me this error:
error: invalid conversion from " int* " to " int "
I want to create a calculatePercentage function, so I can use the value when I call it.
void calculatePercentage(int voteResult[],int percentage[])
const int NO_OF_CANDIDATE = 10;
int main()
{
ifstream input("votes.txt",ios::in);
string candidates[NUMBER_OF_CANDIDATE];
int voteResult[NUMBER_OF_CANDIDATE];
int percentage[NUMBER_OF_CANDIDATE];
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++) {
input >> candidates[i] >> voteResult[i];
}
calculatePercentage(voteResult, percentage); // error happened here.
return 0;
}
void calculatePercentage(int voteResult[],int percentage[])
{
int totalVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++)
{
totalVotes += votes[i];
}
for (int j = 0; j < NUMBER_OF_CANDIDATE; j++)
{
double wk_percentage = static_cast<double>{votes[j])/totalVotes;
percentage[j]=static_cast<int>(wk_percentage*100);
}
}
The code you posted has a bunch of errors.
calculatePercentage() definition is missing the closing ';'
probable name mismatch between NO_OF_CANDIDATE and NUMBER_OF_CANDIDATE
missing #include <fstream> (using ifstream)
missing #include <string>
missing std:: namespace before ifstream and string
votes not declared anywhere (should it be voteResult?)
wrong opening curly bracket instead in static_cast<double>{votes[j])/totalVotes;
...
Let alone the way you do calculation and parameter passing...
The following edited code should compile, not sure if it works as you expected:
#include <fstream>
#include <string>
void calculatePercentage(int voteResult[], int percentage[]);
const int NUMBER_OF_CANDIDATE = 10;
int main()
{
std::ifstream input("votes.txt");
std::string candidates[NUMBER_OF_CANDIDATE];
int voteResult[NUMBER_OF_CANDIDATE];
int percentage[NUMBER_OF_CANDIDATE];
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++) {
input >> candidates[i] >> voteResult[i];
}
calculatePercentage(voteResult, percentage); // error happened here.
return 0;
}
void calculatePercentage(int voteResult[], int percentage[])
{
int totalVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++)
{
totalVotes += voteResult[i];
}
for (int j = 0; j < NUMBER_OF_CANDIDATE; j++)
{
double wk_percentage = static_cast<double>(voteResult[j]) / totalVotes;
percentage[j] = static_cast<int>(wk_percentage*100);
}
}
Also on Ideone.
Thanks for everyone's comment. I skipped some statements and made some typos when posting them. I fixed them as follows. The only error occurred is that still cannot convert " int* " from " int". Just don't know how to solve it.
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void calculatePercentage(int voteResult[],int percentage[]);
const int NUMBER_OF_CANDIDATE = 10;
int main()
{
ifstream input("votes.txt",ios::in);
string candidates[NUMBER_OF_CANDIDATE];
int vote[NUMBER_OF_CANDIDATE];
int percentage[NUMBER_OF_CANDIDATE];
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++) {
input >> candidates[i] >> vote[i];
}
calculatePercentage(voteResult, percentage); // error happened here.
return 0;
}
void calculatePercentage(int voteResult[],int percentage[])
{
int totalVotes = 0;
for (int i = 0; i < NUMBER_OF_CANDIDATE; i++)
{
totalVotes += votes[i];
}
for (int j = 0; j < NUMBER_OF_CANDIDATE; j++)
{
double wk_percentage = static_cast<double>(votes[j])/totalVotes;
percentage[j]=static_cast<int>(wk_percentage*100);
}
}
Related
Trying to create a list of unique grades from a text file. Having issues with the output eliminating duplicates. Currently, I am trying to compare the value of each previous array entry to the next and if they are different, output the result to the outfile, but is just outputs an empty file.
I am also curious if there is an easy fix to change the sorting from 'low to high' into 'high to low'. Thank you in advance.
#include <iostream>
#include <string>
#include <limits>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int testScoreArray[100];
void selectSort(int testScoreArray[], int n);
void fileOutput(int testScoreArray[]);
int main()
{
int n = 100;
ifstream infile;
infile.open("testscoresarrayhomework.txt");
for (int i = 0; i < 100; i++) {
infile >> testScoreArray[i];
}
selectSort(testScoreArray, n);
fileOutput(testScoreArray);
infile.close();
return 0;
}
void selectSort(int testScoreArray[], int n)
{
//pos_min is short for position of min
int pos_min, temp;
for (int i = 0; i < n - 1; i++) {
pos_min = i; //set pos_min to the current index of array
for (int j = i + 1; j < n; j++) {
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
//pos_min will keep track of the index that min is in, this is needed when a swap happens
}
//if pos_min no longer equals i than a smaller value must have been found, so a swap must occur
if (pos_min != i) {
temp = testScoreArray[i];
testScoreArray[i] = testScoreArray[pos_min];
testScoreArray[pos_min] = temp;
}
}
};
void fileOutput(int testScoreArray[])
{
ofstream outfile;
int gradeEvent = 0;
int previousGrade = 0;
outfile.open("testscoresoutput.txt");
outfile << "Test Score Breakdown: ";
outfile << endl
<< "Score / Occurance";
for (int i = 0; i < 100; i++) {
previousGrade = i;
if (previousGrade && previousGrade != i) {
outfile << '\n' << testScoreArray[i] << " / " << gradeEvent;
}
}
outfile.close();
};
You have declared a global variable testScoreArray and the function names use the same variable name for their parameters. It's best to avoid using global variables when possible. You can remove global declaration, then declare testScoreArray in main, and pass it to your functions. Example:
//int testScoreArray[100]; <=== comment out
void selectSort(int *testScoreArray, int n);
void fileOutput(int *testScoreArray, int n); //add array size
int main()
{
int testScoreArray[100]; //<== add testScoreArray in here
int n = sizeof(testScoreArray) / sizeof(testScoreArray[0]);
selectSort(testScoreArray, n);
fileOutput(testScoreArray, n);
...
}
In fileOutput you are basically checking to see if i != i, you need to examine the array, not indexing in the loop:
void fileOutput(int *testScoreArray, int n)
{
ofstream outfile("testscoresoutput.txt");
for(int i = 0; i < n; i++)
if(i && testScoreArray[i] != testScoreArray[i-1])
outfile << testScoreArray[i] << "\n";
};
To revers the sort, simply change the condition in this comparison
if (testScoreArray[j] < testScoreArray[pos_min])
pos_min = j;
To:
if(testScoreArray[j] > testScoreArray[pos_min])
pos_min = j;
Technically you would rename the variable to pos_max
So I have my program here:
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
int const size = 3;
struct Arguments{
int array[];
float result1[];
float result2[];
};
//void calc(int arr[], float rarr1[], float rarr2[], int size);
void* calc(void *param);
int main(int argc, char *argv[]){
time_t t;
srand((unsigned) time(&t));
int arr[size][size] = {};
float rarr1[size][size-1] = {};
float rarr2[size][size-1] = {};
for(int x = 0; x < size; x++){
for(int y = 0; y < size; y++){
int number = rand()%10;
arr[x][y] = number;
}
}
for(int x = 0; x < size; x++){
for(int y = 0; y < size; y++){
cout << arr[x][y] << " ";
}
cout << endl;
}
cout << endl;
/////////////////////////////////////////
pthread_t child;
struct Arguments input;
for(int i = 0; i < size; i++){
input.array[i] = arr[0][i];
}
pthread_create(&child, NULL, calc, (void*)&input);
pthread_join(child, NULL);
//calc(&input);
for(int i = 0; i < size-1; i++){
rarr1[0][i] = input.result1[i];
cout << "Test: " << rarr1[0][i] << endl;
}
//////////////////////////////////
return 0;
}
//void calc(int arr[], float rarr1[], float rarr2[], int size){
void* calc(void *param){
struct Arguments *input = (struct Arguments*)param;
int arr1[] = {};
float rarr1[] = {};
float rarr2[] = {};
for(int i = 0; i < size; i++){
arr1[i] = input->array[i];
}
for(int i = 0; i < size; i++){
int a = arr1[i];
int b = arr1[i+1];
int difference = a-b;
if(difference < 0){
difference = difference * -1;
}
float euc = 1 + pow(difference, 2);
euc = sqrt(euc);
rarr1[i] = euc;
}
for(int i = 0; i <size-1; i++){
input->result1[i] = rarr1[i];
}
for(int i = 0; i <size-1; i++){
int a = arr1[i];
int b = arr1[i+1];
int difference = a-b;
if(difference < 0){
difference = difference * -1;
}
float apar = (difference/rarr1[i]);
float result = asin(apar);
result = result*(180/3.14);
rarr2[i] = result;
}
return NULL;
}
The important part that causes the trouble is between ////// lines but I left the rest of the code for the context, since it might be useful.
So I have the function calc(param); that does the important calculation in the program.
It is working just fine as long as I call it myself (by actually including the function call in the code) and the test loop right after it gives the correct results.
However, when I try to use pthread_create(); to create a new thread that will take care of executing that function, the test loop spits out nonsense and some random huge numbers different each time.
It's kinda weird because the code compiles either way, and literally the only thing that I change is these 2 lines.
What am I doing wrong and why the function spits out garbage when started by the Pthread? Is there a way to fix it?
Ok so if anyone's having a similar problem:
Declare the size of arrays no matter what. It turns out that my program didn't work properly because I initialized my result arrays as float result1[]; instead of float result1[size];
I have created a function that returns the sum of all the numbers in an array, however I keep getting an error message: error: invalid conversion from 'int (*)[6]' to 'int' [-fpermissive]. In addition I also get an error that says: error: initializing argument 1 of 'int getTotal(int)'[-fpermissive]. It seems like these two errors go together. Am I supposed to use pointers? I have spent hours trying to figure this out with no luck.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
const int ROWS = 4;
const int COLS = 6;
void openInputFile(ifstream &,string);
int getTotal(int);
using namespace std;
int main()
{
int tot; //total of all numbers
int val;
int twoArray[ROWS][COLS];
ifstream inFile;
string inFileName = "nums.txt";
//Opening file
openInputFile(inFile, inFileName);
//Create 2D array
for(int i=0; i<ROWS; i++)
{
for(int j=0; j<COLS; j++)
{
inFile >> twoArray[i][j];
}
}
//Close
inFile.close();
//THIS IS WHERE ERROR IS
tot = getTotal(twoArray);
printArray(twoArray);
return 0;
}
void openInputFile(ifstream &inFile, string theFile)
{
inFile.open(theFile.c_str());
if(!inFile)
{
cout << "Error opening the file!\n";
exit(13);
}
}
int getTotal(int array[][COLS])
{
int sum = 0;
for(int i=0; i<ROWS; i++)
{
for(int j=0; j<COLS; j++)
{
sum+=array[i][j];
}
}
return sum;
}
int printArray(int array[][COLS])
{
for(int i=0; i<ROWS; i++)
{
for(int j=0; j<COLS; j++)
{
cout << array[i][j] << " ";
}
cout << endl;
}
return 0;
}
The problem is in wrong function declaration. You have at the beginning of code:
int getTotal(int);
and then define function as:
int getTotal(int array[][COLS])
So, edit your functions' declaration. By the way I cannot see declaration for:
int printArray(int array[][COLS]);
I have modified the code from my previous question, and now it looks like this:
//#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <chrono>
#include <cassert>
using namespace std;
const int MAX_SIZE=10000;
const int MAX_STRINGS = 10;
char** strings=new char*[10];
int len;
char* GetLongestCommonSubstring( char* str1, char* str2 );
inline void readNumberSubstrings();
inline const char* getMaxSubstring();
void readNumberSubstrings()
{
cin >> len;
assert(len >= 1 && len <=MAX_STRINGS);
for(int i=0; i<len;i++)
strings[i]=new char[MAX_SIZE];
for(int i=0; i<len; i++)
cin >> strings[i];
}
const char* getMaxSubstring()
{
char *maxSubstring=strings[0];
auto begin = chrono::high_resolution_clock::now();
for(int i=1; i < len; i++)
maxSubstring=GetLongestCommonSubstring(maxSubstring, strings[i]);
cout << chrono::duration_cast <chrono::milliseconds> (chrono::high_resolution_clock::now()-begin).count() << endl;
return maxSubstring;
}
char* GetLongestCommonSubstring( char* string1, char* string2 )
{
if (strlen(string1)==0 || strlen(string2)==0) cerr << "error!";
int *x=new int[strlen(string2)+ 1]();
int *y= new int[strlen(string2)+ 1]();
int **previous = &x;
int **current = &y;
int max_length = 0;
int result_index = 0;
int length;
int M=strlen(string2) - 1;
for(int i = strlen(string1) - 1; i >= 0; i--)
{
for(int j = M; j >= 0; j--)
{
if(string1[i] != string2[j])
(*current)[j] = 0;
else
{
length = 1 + (*previous)[j + 1];
if (length > max_length)
{
max_length = length;
result_index = i;
}
(*current)[j] = length;
}
}
swap(previous, current);
}
delete[] x;
delete[] y;
string1[max_length+result_index]='\0';
return &(string1[result_index]);
}
int main()
{
readNumberSubstrings();
cout << getMaxSubstring() << endl;
return 0;
}
It's still solving the generalised longest common substring problem, and now it's rather fast.
But there's a catch: if a user specifies, say, 3 as a number of strings he's about to enter, and then only actually enters one string, this code waits forever.
How do I change that?
If you read from a file and the number of arguments isn't equal to the number of arguments provided, just print a nice, clean error message to the user.
"Expected 7 arguments, received 3:"
Print out the arguments you found so the user has an idea of what the program is looking at when it spits out the error.
As for human input, I agree with the comments. The program should wait until the user close it or enters all the needed arguments.
I've got this code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr;
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
vecptr->push_back(temp);
}
veclen = vecptr->size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<vecptr[i]<<endl;
}
return 0;
}
My compiler(G++) throw me some errors: test2.cpp:28:17: error: no match for 'operator<<' in 'std::cout << *(vecptr + ((unsigned int)(((unsigned int)i) * 12u)))' ...
What's wrong? What can I do to fix it?
The program is still not completely right. You have to initialize the vector pointer and then give it a size and the use it. A full working code could be,
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> *vecptr = new vector<string>(10);
int veclen;
void getinput()
{
string temp;
for(int i = 0; i < 3; i++)
{
cin>>temp;
(*vecptr)[i] = temp;
}
veclen = (*vecptr).size();
}
int main()
{
getinput();
for(int i = 0; i < veclen; i++)
{
cout<<(*vecptr)[i]<<endl;
}
return 0;
}
Although I have mentioned the size as 10 you could make it a variant.
You need to dereference vecptr here to get the underlying vector:
cout << (*vecptr)[i] << endl;
You will also need to initialize vecptr.