- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在以下代码中为“候选”结构
编制索引?当我尝试打印创建的结构的最后一个成员(最后一个索引?)时,它是 candidates["last index"].name 假设我确实有 4 个候选人,这将导致 candidate_count = argc - 1
等于 4,所以,我认为如果我通过索引 4 访问第 4 个成员,我应该到达空终止符,对吗?但那没有发生!代码看起来像这样
(在程序末尾找到)
printf("Winner is %s", candidates[4].name);
并且它完美地打印了候选人姓名数组的第 4 个成员姓名!那个怎么样?不应该是这样吗
printf("Winner is %s", candidates[3].name)
这是我写的完整程序:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
// Max number of candidates
#define MAX 9 // define MAX as a constant = 9 (or any number which might be used without '=' sign).
// define syntax won't allocate any memory for the constant 'MAX', it can be used later as int MAX
// which = int 9
// Candidates have name and vote count, stuct is the best to use to create a custom data type.
typedef struct
{
string name;
int votes;
}
candidate;
// Array of candidates
candidate candidates[MAX];
// Number of candidates as a global variable
int candidate_count;
// Function prototypes
bool vote(string name);
void print_winner(void);
int main(int argc, string argv[])
{
// Check for invalid usage, the args. must be more than 2, i.e 3 and up!
if (argc < 2)
{
printf("Usage: plurality [candidate ...]\n");
return 1;
}
// Populate array of candidates
candidate_count = argc - 1; // -1 because one argument is the program's name. the rest are the
// candidates' names.
if (candidate_count > MAX)
{
printf("Maximum number of candidates is %i\n", MAX);
return 2; // err code 2 means that the candidates number is exceeded
}
for (int i = 0; i < candidate_count; i++) // Store the candidates names from the argv[] into,
// the struct candidate of candidates.name[] array to be globally available.
{
candidates[i].name = argv[i + 1]; // +1 because the 0th index is the programs name.
candidates[i].votes = 0; // initializing 0 for all candidates
}
// Enter the number of people allowed to vote, in other words, total number of votes allowed.
int voter_count = get_int("Number of voters: ");
// Loop over all voters to enter their votes for a candidate of the available names.
for (int i = 0; i < voter_count; i++)
{
string name = get_string("Vote: ");
// Check for invalid vote
if (!vote(name)) // Use function vote(string name) to check for the presence,
//of the candidate's name.
{
printf("Invalid vote.\n");
}
}
// Display winner of election
print_winner(); // call this func. to print the winner's name.
}
// Update vote totals given a new vote
bool vote(string name)
{ // loop over all candidates names checking it's availability by comparing it to user-entered name.
// global variable candidate_count is used to keep track of number of candidates.
for (int i = 0; i < candidate_count ; i++)
{
if (strcmp (name, candidates[i].name) == 0)
{
// Update the candidate's vote count.
candidates[i].votes++; // update the votes count for the candidate indexed @ i.
return true;
}
} // End for() iteration over the candidates names indeces.
return false;
}
// Print the winner (or winners) of the election
void print_winner(void)
/*
Bubble sorting Algorithm;
- A pass is a number of steps where the adjacent elements are compared to eachother from left to right in
an int array each one with the one next to it.
- If an array has a number of elements of 5, so, n = 5.
- There will always be a maximum of n - 1 passes in bubble sorting
- There will be a maximum of n - 1 comparisons of items in each pass if code is not optimized
*/
{
int swap = 0; // A flag to check if swapping happened.
//( To check if the array is sorted, swap happening = not sorted yet else the array is sorted)
for (int i = 0; i <= candidate_count - 1; i++) // passes = n - 1 where n = number of elements to compare.
{
for (int j = 0; j <= candidate_count - 1 - i; j++) // Number of comparisions(elements to be checked -
// with thier adjacent ones) to be conducted in each pass, after pass the last element will always
// be the greatest element there for no need to compare it with the element before it. therefore,
// candidate_count - 1 - i where i value starting form 0 by the outer for loop reduces the number -
// of steps or elements to be checked each iteration
{
/* if the first candidate number of votes element in the array is Greater-Than the adjacent next
one, swap them and keep a flag or indicate that you did swap them.
*/
if ( candidates[j].votes > candidates[j + 1].votes)
{
// Swap the position of the struct candidates elements inside
candidate temp = candidates[j];
candidates[j] = candidates[j + 1];
candidates[j + 1] = temp;
swap = 1; // a flag to indicated the swapping actually happened.
} // End swapping if() statement.
}
if (swap == 0) // if no swapping happened
break;
}
/* When Populating array of candidates, candidate_count = argc - 1; // -1 because one argument
is the program's name. the rest are the candidates' names.
*/
printf("Winner is %s, candidate count = %d \n", candidates[candidate_count].name, candidate_count);
return;
}
从评论中复制:
如果我在终端中运行该程序并添加“printf”来打印从索引 0 到 5 开始的候选人姓名和选票,这就是我得到的结果:
c ~/pset3/plurality/ $ ./plurality moh zoz sos
Number of voters: 5
Vote: moh
Vote: moh
Vote: moh
Vote: zoz
Vote: sos
Winner is moh, candidate count = 3
The candidate name : (null) votes : 0
The candidate name : zoz votes : 1
The candidate name : sos votes : 1
The candidate name : moh votes : 3
The candidate name : (null) votes : 0
The candidate name : (null) votes : 0
解决方案只是从该行的条件中删除“等于”:
for (int j = 0; j <= candidate_count - 1 - i; j++)
看起来像这样
for (int j = 0; j < candidate_count - 1 - i; j++)
最佳答案
您的冒泡排序有错误。
第二个循环的条件是j <= candidate_count - 1 - i
但应该是j <= candidate_count - 2 - i
.这是因为您交换了 j
处的元素和 j+1
.但是以你的情况j == candidate_count - 1
这导致交换 candidate_count-1
和 candidate_count
.
要找到此类错误,您应该学习如何使用调试器或将调试输出添加到您的程序中,例如
printf("swap(%d, %d)\n", j, j+1);
然后您可以更好地了解您的程序实际做了什么。
作为旁注:candidates
的排序没有必要,因为您可以简单地遍历数组并搜索具有最大 vote
的候选者,比如:
if (candidate_count < 1) {
// some error handling
} else {
candidate biggest = candidates[0];
for (int i = 1; i < candidate_count; i++) {
if (biggest.vote < candidates[i].vote) {
biggest = candidates[i];
}
}
// do what ever you want to do with the winner
}
关于c - 如何索引 "struct"成员?如何在 C 中正确访问它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63133836/
我有一个数组 items[] items[] 中的每一项都是一个结构体。 item 有键 id、date、value(即 item.id、item.date、item.value) 我想使用 Stru
我想存储 100 名员工。 RollNo,姓名,工资,时间(各种数据,我无法在这里解释,但你可以看下面的代码片段来理解 main() { struct day { int hour
这个问题在这里已经有了答案: storage size of ‘names’ isn’t known (3 个答案) 关闭 5 年前。 我正在尝试蓝牙编程,遇到了这个我不明白的问题。基本上,当我使用
这是一个奇怪的事情: 我有一个结构,它包含指向相同类型结构的指针和指向其他类型结构的指针,以及一些其他值。 struct animal { struct animal * father;
我有一个结构定义如下(名称不同) struct str1 { int field1; struct str2; } 我在一个函数中有一个*str1。我想要一个指向 str2 的指针。 所以
DISK_DETECTION_INFO is defined as有什么原因吗? typedef struct _DISK_DETECTION_INFO { DWORD Size
我正在尝试打包一个字符串和一个字符串的长度。 fmt = '
我在创建结构时遇到问题。 我的结构: public struct Device: Codable { let data: DeviceData let meta: Meta? } pu
struct Item { var name:String? var type:String? var value:Int? var tag:Int? } ... ..
// NewReaderSize returns a new Reader whose buffer has at least the specified 43 // size. If the ar
这个问题在这里已经有了答案: Sorting a vector of custom objects (14 个答案) 关闭 3 年前。 在下面的 C++ 片段中, 如何基于 TwoInts 结构中的
#include struct Header { unsigned long long int alignment; }; int main(void) { struct Heade
我有一个目前看起来像这样的结构(缩写为仅显示基本部分): typedef struct { uint32_t baudrate; ... some other internally u
对此没有太多解释,这就是我所拥有的: public struct PACKET_HEADER { public string computerIp; publi
我有以下代码: struct MyStruct{ data: &'a str, } fn get(S: &'a MyStruct) -> &'a str{ S.data } fn se
struct S1 { char c; int i; }; struct S3 { char c1; struct S1 s; double c2; }; 我正
我有一个名为 Parameter 的协议(protocol): protocol Parameter { var name: String { get } var unit: Unit
有 2 个 struct 定义 A 和 A。我知道 struct A 可以包含指向 struct A 的 POINTER 但我不明白为什么 struct A 不能包含struct A(不是指针) 最佳
我有以下代码: struct MyStruct{ data: &'a str, } fn get(S: &'a MyStruct) -> &'a str{ S.data } fn se
为了说明这一点,这里有一个小的不可变结构和一个更新它的函数: (struct timeseries (variable observations) #:transparent) (define (ad
我是一名优秀的程序员,十分优秀!