C编程用于循环和计数器

时间:2014-03-01 04:38:40

标签: c

我正在尝试制作一个程序来计算你需要赢得多少个州。我已完成它的主要部分,但现在我正在尝试制作一个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", &current_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;

}

1 个答案:

答案 0 :(得分:5)

你的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++;
}