Trouble accessing value in array of structs - c

I am having trouble with this code. In particular I can't seem to figure out why it is that the voteFractions() function doesn't work for me. It gets called appropriately, and all the correct parameters seem to reach the function, but I cannot get anything from "candidates[i].votes_fraction = candidates[i].votes/total;". All I ever get for candidates[i].votes_fraction is 0.00.
I tried running the program with NUMBER_OF_CANDIDATES = 1, and everything runs OK when that is the case, so I feel like I may be doing something silly, but I just can't seem to see it...
#define NUMBER_OF_CANDIDATES 10
typedef struct candidate{
char name[20];
int votes;
float votes_fraction;
} candidate;
int totalVotes(candidate *candidates)
{
int total = 0;
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
total += candidates[i].votes;
return total;
}
void voteFractions(candidate *candidates, int total, char *winner)
{
float most_votes = 0, test;
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
{
candidates[i].votes_fraction = candidates[i].votes/total;
if (candidates[i].votes_fraction > most_votes)
{
most_votes = candidates[i].votes_fraction;
strcpy(winner, candidates[i].name);
}
}
}
int main()
{
candidate candidates[NUMBER_OF_CANDIDATES];
int total;
char winner[20];
for (int i = 0; i<NUMBER_OF_CANDIDATES; i++)
{
printf("Enter candidate's name and the number of votes received: ");
scanf("%s %d", candidates[i].name, &candidates[i].votes);
}
total = totalVotes(candidates);
voteFractions(candidates, total, winner);
return 0;
}

The problem is that in this statement
candidates[i].votes_fraction = candidates[i].votes/total;
expression
candidates[i].votes/total
uses integer arithmetic because the both operands have type int. As total is always greater than or equal to candidates[i].votes then the result of the division is equal to 0. You have to write
( float )candidates[i].votes/total
Take into account that variable test is declared but not used in function voteFractions. You may remove it.
void voteFractions(candidate *candidates, int total, char *winner)
{
float most_votes = 0, test;
//...

Related

How to initialize a field in a struct from another struct? C

So im new to C programming and my assignment is to write a function(Max_way) that prints the driver who had the total of longest trips.
im using these 2 structs:
#define LEN 8
typedef struct
{
unsigned ID;
char name[LEN];
}Driver;
typedef struct
{
unsigned T_id;
char T_origin[LEN];
char T_dest[LEN];
unsigned T_way;
}Trip;
and a function to determine the total trips of a certain driver:
int Driver_way(Trip trips[], int size, unsigned id)
{
int km=0;
for (int i = 0; i < size; i++)
{
if (id == trips[i].T_id)
{
km = km + trips[i].T_way;
}
}
return km;
}
but when im trying to print the details of a specific driver from an array of drivers, i receive the correct ID, the correct distance of km, but the driver's name is not copied properly and i get garbage string containing 1 character instead of 8.
i've also tried strcpy(max_driver.name,driver[i].name) with same result.
void Max_way(Trip trips[], int size_of_trips, Driver drivers[], int size_of_drivers)
{
int *km;
int max = 0;
Driver max_driver;
km = (int*)malloc(sizeof(int) * (sizeof(drivers) / sizeof(Driver)));
for (int i = 0; i < size_of_drivers; i++)
{
km[i] = Driver_way(trips, sizeof(trips), drivers[i].ID);
for (int j = 1; j < size_of_drivers; j++)
{
if (km[j] > km[j - 1])
{
max = km[j];
max_driver.ID = drivers[i].ID;
max_driver.name = drivers[i].name;
}
}
}
printf("The driver who drove the most is:\n%d\n%s\n%d km\n", max_driver.ID, max_driver.name, max);
}
any idea why this is happening?
Note that one cannot copy a string using a simple assignment operator; you must use strcpy (or similar) as follows:
if (km[j] > km[j - 1]) {
max = km[j];
max_driver.ID = drivers[i].ID;
strcpy(max_driver.name,drivers[i].name);
}
Also note that since you were using ==, this was not even a simple assignment, put a comparison. Changing to == likely fixed a compile-time error, but it did NOT give you what you want.

Why is my CS50 code not working and why my code keeps overflowing or giving a value of 1?

I am working on the "greedy" algo in CS50. I am not sure what's wrong but it keeps giving me a value of 1 or overflowing when I input a value.
Please see below:
#include<cs50.h>
#include<stdio.h>
#include<math.h>
int main(void)
{
//define variables
float change;
do
{
change=get_float("change: ");
}
while(change<= 0);
// change float to integer define variable
int amount = round (change*100);
// define the possible coins with each situation
int a1,b,c,d;
a1=amount/25;
b=(amount-a1*25)/10;
c=(amount-a1*25-b*10)/5;
d=(amount-a1*25-b*10-c*5)/1;
//
while (amount>=25)
{
int a1_count++;
}
while (amount>10&&amount<25)
{
int b_count++;
}
while (amount>5&&amount<10)
{
int c_count++;
}
while ( amount>1&& amount<5)
{
int d_count++;
}
// total of the coins been used
int coins= a1_count+b_count+c_count+d_count;
printf("number of coins given: %i\n",coins);
}
You are initializing your "count" values inside your while loops, so each time the loop runs it create a count variable that is local to this loop.
When the loop ends the variable is destroyed, meaning you can't access it outside the while loop.
int main(void)
{
//define variables
float change;
do
{
change=get_float("change: ");
}
while(change<= 0);
// change float to integer define variable
int amount = round (change*100);
// define the possible coins with each situation
int a1,b,c,d;
a1=amount/25;
b=(amount-a1*25)/10;
c=(amount-a1*25-b*10)/5;
d=(amount-a1*25-b*10-c*5)/1;
//
int a1_count = 0, b_count = 0, c_count = 0, d_count = 0;
while (amount>=25)
{
a1_count++;
amount -= 25;
}
while (amount>10&&amount<25)
{
b_count++;
amount -= 10;
}
while (amount>5&&amount<10)
{
c_count++;
amount -= 5;
}
while ( amount>1&& amount<5)
{
d_count++;
amount -= 1;
}
// total of the coins been used
int coins= a1_count+b_count+c_count+d_count;
printf("number of coins given: %i\n",coins);
}

Changing the contents of an array in a recursive function

I am having trouble understanding something regarding recursion and arrays.
basically, what the program does is to check what is the maximum weights of items that can be placed in two boxes. I know it's far from perfect as it is right now, but this is not the point.
Generally everything is working properly, however, now I decided that I want to see the contents of each box when the weight is maximal. For this purpose I tried using arr1 and arr2.
I don't understand why I get different results for arr1 and arr2 (the first options gives me what I want, the second does not).
This is the program:
#define N 5
int help(int items[N][2], int box1[N], int box2[N], int rules[N][N],
int optimal,int current_weight,int item,int arr1[],int arr2[])
{
if (item == N)
{
if(current_weight>optimal) //This is the first option
{
memcpy(arr1,box1,sizeof(int)*N);
memcpy(arr2,box2,sizeof(int)*N);
}
return current_weight;
}
int k = items[item][1]; int sol;
for (int i = 0; i <= k; i++)
{
for (int j = 0; i+j <= k; j++)
{
box1[item] += i; box2[item] += j;
if (islegal(items, box1, box2, rules))
{
sol = help(items, box1, box2, rules, optimal,
current_weight + (i + j)*items[item][0],item+1,arr1,arr2);
if (sol > optimal)
{
optimal = sol;
memcpy(arr1,box1,sizeof(int)*N); //This is the second option
memcpy(arr2,box2,sizeof(int)*N);
}
}
box1[item] -= i; box2[item] -= j;
}
}
return optimal;
}
int insert(int items[N][2], int rules[N][N])
{
int box1[N] = { 0 }; int arr1[N] = { 0 };
int box2[N] = { 0 }; int arr2[N] = { 0 };
int optimal = 0;
int x = help(items, box1, box2, rules,0, 0,0,arr1,arr2);
print(arr1, N);
print(arr2, N);
return x;
}
Can anyone explain what causes the difference? Why the first option is correct and the second is not? I couldn't figure it out by my own.
Thanks a lot.
This doesn't work because when you pass box1 and box2 to help, they are mutated by help. It's pretty obvious from the algorithm that you want them to not be mutated. So, we can do as follows:
int help(int items[N][2], int box1in[N], int box2in[N], int rules[N][N],
int optimal,int current_weight,int item,int arr1[],int arr2[])
{
int box1[N];
int box2[N];
memcpy(box1, box1in, sizeof(int)*N);
memcpy(box2, box2in, sizeof(int)*N);
Your algorithm may still have problems but that problem is now removed.

Understanding returning values functions C

I'm trying to understand how the return value of a function works, through the following program that has been given to me,
It goes like this :
Write a function that given an array of character v and its dim, return the capital letter that more often is followed by its next letter in the alphabetical order.
And the example goes like : if I have the string "B T M N M P S T M N" the function will return M (because two times is followed by N).
I thought the following thing to create the function:
I'm gonna consider the character inserted into the array like integer thank to the ASCII code so I'm gonna create an int function that returns an integer but I'm going to print like a char; that what I was hoping to do,
And I think I did, because with the string BTMNMPSTMN the function prints M, but for example with the string 'ABDPE' the function returns P; that's not what I wanted, because should return 'A'.
I think I'm misunderstanding something in my code or into the returning value of the functions.
Any help would be appreciated,
The code goes like this:
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int trovato;
for(int j=0;j<DIM-1;j++) {
if (a[j]- a[j+1]==-1) {
trovato=a[j];
}
}
return trovato;
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("%c",maxvolte(v,dim));
return 0;
}
P.S
I was unable to insert the value of the array using in a for scanf("%c,&v[i]) or getchar() because the program stops almost immediately due to the intepretation of '\n' a character, so I tried with strings, the result was achieved but I'd like to understand or at least have an example on how to store an array of character properly.
Any help or tip would be appreciated.
There are a few things, I think you did not get it right.
First you need to consider that there are multiple pairs of characters satisfying a[j] - a[j+1] == -1
.
Second you assume any input will generate a valid answer. That could be no such pair at all, for example, ACE as input.
Here is my fix based on your code and it does not address the second issue but you can take it as a starting point.
#include <stdio.h>
#include <assert.h>
int maxvolte(char a[],int DIM) {
int count[26] = {0};
for(int j=0;j<DIM-1;j++) {
if (a[j] - a[j+1]==-1) {
int index = a[j] - 'A'; // assume all input are valid, namely only A..Z letters are allowed
++count[index];
}
}
int max = -1;
int index = -1;
for (int i = 0; i < 26; ++i) {
if (count[i] > max) {
max = count[i];
index = i;
}
}
assert (max != -1);
return index + 'A';
}
int main()
{
int dim;
scanf("%d",&dim);
char v[dim];
scanf("%s",v);
printf("answer is %c\n",maxvolte(v,dim));
return 0;
}
#include <stdio.h>
int maxvolte(char a[],int DIM) {
int hold;
int freq;
int max =0 ;
int result;
int i,j;
for(int j=0; j<DIM; j++) {
hold = a[j];
freq = 0;
if(a[j]-a[j+1] == -1) {
freq++;
}
for(i=j+1; i<DIM-1; i++) { //search another couple
if(hold==a[i]) {
if(a[i]-a[i+1] == -1) {
freq++;
}
}
}
if(freq>max) {
result = hold;
max=freq;
}
}
return result;
}
int main()
{
char v[] = "ABDPE";
int dim = sizeof(v) / sizeof(v[0]);
printf("\nresult : %c", maxvolte(v,dim));
return 0;
}

Very Simple C Program Crashing

I'm having a simple issue where my C executable is crashing after attempting to grab input from the user.
The idea of the program is to populate an array and eventually generate some data on that array. So far I have attempted to grab input from the user and immediately after the exe crashes. I've also edited the code temporarily whilst trying to debug what the issue is with no success. I have not touched c in a number of years and was very young when I had last and am quite a novice.
Can someone advise on any possible solution to why it would be crashing?
#include <stdio.h>
#include <stdbool.h>
double get_double(char prompt[50])
{
double tempDouble = 0;
printf("%s", prompt);
scanf("%d", tempDouble);
return tempDouble;
}
void populate_array(double *pData[])
{
int i = 0;
*pData[0] = get_double("Please Enter A Number : ");
//for(i = 0; i < sizeof(*pData); i++)
//{
//*pData[i] = get_double("Please Enter A Number : ");
//}
}
double get_sum(double data[10])
{
int i = 0;
double result = 0;
for (i = 0; i < sizeof(data); i++)
{
result += data[i];
}
return result;
}
int main()
{
//Variable Declarations
bool running = true;
bool playAgain = false;
double numbers[10];
double sum, min, max, var, dev;
//Process
populate_array(&numbers);
sum = get_sum(numbers);
printf("%d",sum);
}
void populate_array(double *pData[]) accepts an array of pointer, while you pass it just an array, it should be:
void populate_array(double pData[])
{
int i = 0;
pData[0] = get_double("Please Enter A Number : ");
}
Also, when you read the double, it should be:
// as proposed by Jonathan, the format string should contain '%lf' for double, I overlooked it.
scanf("%lf", &tempDouble);
if you pass scanf just tempDouble, it treats its value as an address, which is invalid address of course.
Your code contains:
scanf("%d", tempDouble);
You need to add & to the parameter you use in scanf().
And %d is used with integer. When you want to use double you need to use %lf; with a float, you'd use %f.
for (i = 0; i < sizeof(data); i++)
this will iterate after you reached the boundaries of the array.
for (i = 0; i < sizeof(data)/sizeof(double); i++)
this may be works but is not elegant
double get_sum(int numberOfElements, double data[10])
{
int i = 0;
double result = 0;
for (i = 0; i < numberOfElements; i++)
{
result += data[i];
}
return result;
}
this is the better approach
sum = get_sum(10, numbers);
In the main function call the get_sum function like this

Resources