2014-03-01 86 views
1

我正在嘗試編寫一個程序,計算您需要贏得多少個狀態。我已經完成了它的主要部分,但現在我試圖做一個FOR循環,基本上檢查您現在有多少票的總和加上該州的選票數大於270,即贏的數量。之後,我試圖打印,如果你贏得這個狀態,你會贏。最後它會計算並打印出您可以贏得多少種方式。這是迄今爲止我所知道的,但是當我給他們打電話時,它並沒有說那個國家的名字,也沒有給出我可以贏得多少種方式的一個,兩個或三個數字,只是一個大數字我沒有儲存。C編程for循環和計數器

任何人都可以幫助我嗎?

#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

開始宣佈'name_state_1'和'name_state_2'爲'char'陣列。 –

+0

它似乎是一個混合,包括* python *和* shell * ... –

回答

5

你如果包含空語句

if(current_votes + num_votes_1 >= 270); 

IF塊的卸下;

c也沒有像Python,壓痕不作代碼的一部分。

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++; 
} 
+0

也初始化變量,如評論打算..'int x = 0;' – Gishu

+0

@Gishu是錯過了一個呵呵 –