我正在尝试编写一个程序来计算你需要多少个州才能获胜。我已经完成了主要部分,但现在我正在尝试创建一个FOR循环,它基本上检查您现在拥有的票数加上该州拥有的票数之和是否大于270,即获胜的票数。在那之后,我试着打印,如果你赢了这个州,你就会赢。最后,它将计算并打印出您可以获胜的方法。到目前为止,这就是我所知道的,但当我调用它们时,它没有说出州的名称,它也没有给我一个1,2或3个数字来表示你能赢的方式,只给了一个我没有存储的大数字。
有谁可以帮我?
#include <stdio.h>
int main(void){
//Initialize your variables
int current_votes, num_votes_1, num_votes_2, x;
char name_state_1, name_state_2;
//ask the user for the current number of electoral votes their candidate has
printf("How many electoral votes has your candidate won?\n");
scanf("%d", ¤t_votes);
//Now ask for the first state in contention
printf("What is the name of the first state in contention?\n");
scanf("%s", &name_state_1);
//now ask hiw many electoral votes the first state has
printf("How many electoral votes does it have?\n");
scanf("%d", &num_votes_1);
//now ask for the second state in contention
printf("What's the name of the second state in contention?\n");
scanf("%s", &name_state_2);
//now ask how many electoral votes the second state has
printf("How many electoral votes does it have?\n");
scanf("%d", &num_votes_2);
//Now here's the formula that checks to see if you win in each state
//and counts how many ways you can win
for(x = 0; x < 3; x++) {
if(current_votes + num_votes_1 >= 270);
printf("Your candidate wins if he/she wins %s", &name_state_1);
x++;
if(current_votes + num_votes_2 >= 270);
printf("Your candidate wins if he/she wins %s", &name_state_2);
x++;
if(current_votes + num_votes_1 + num_votes_2 >= 270);
printf("your candidate wins if he/she wins %s", &name_state_1, &name_state_2);
x++;
}
//now call to tell how many ways the candidate can win overall
printf("your candidate can win %d ways", &x);
return 0;
}发布于 2014-03-01 12:42:27
您的if包含空语句
if(current_votes + num_votes_1 >= 270);删除;
而且,c不像python,缩进不会使代码成为if块的一部分。
if(current_votes + num_votes_1 >= 270)
printf("Your candidate wins if he/she wins %s", &name_state_1);
x++;将始终执行x++。只有printf部分是if块的一部分。使用{}封装代码。
最后,您还打印了x的地址,这就是它是一个大数字的原因。最后,使用x来计算获胜的方式并作为循环条件并不是一个好主意。在我看来,你甚至不需要这个循环。
这似乎足够了:
x = 0;
if(current_votes + num_votes_1 >= 270);
{
printf("Your candidate wins if he/she wins %s", &name_state_1);
x++;
}
if(current_votes + num_votes_2 >= 270);
{
printf("Your candidate wins if he/she wins %s", &name_state_2);
x++;
}
if(current_votes + num_votes_1 + num_votes_2 >= 270);
{
printf("your candidate wins if he/she wins %s", &name_state_1, &name_state_2);
x++;
}https://stackoverflow.com/questions/22110196
复制相似问题