簡體   English   中英

C 程序在 For 循環中崩潰

[英]C Program crashes at For Loop

我是 C 編程的新手(我有一些非常基本的通過 vb.NET 編程的經驗),我正在嘗試為 Project Euler Problem #1 編寫程序。 https://projecteuler.net/problem=1

算法

挑戰要求程序員找到 1000 以下的所有 3 或 5(含)的倍數之和(我使用 intInput 來允許用戶輸入一個整數來代替 1000)。

我當前的解決方案接受輸入,並將其遞減 1,直到 (intInput - n) % 3 = 0,即,直到找到輸入整數下的下一個最接近的 3 倍數。

然后程序循環遍歷從 1 到 ((intInput - n) / 3) 的所有整數,將每個整數與前面整數的和相加,只要當前整數不是 5 的倍數,在這種情況下,它是跳過。

然后將結果和存儲在 intThreeMultiplier 中。

然后重復上面的過程,用5代替3找到intInput下5的最大倍數,然后循環整數1到((intInput - n) / 5),這次不跳過3的倍數,並存儲intFiveMultiplier 中的總和。

然后通過 sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier) 計算輸出總和。

問題

每當我編譯和運行我的代碼時,允許用戶輸入一個整數,然后程序崩潰。 我已經確定原因與第一個 For 循環有關,但我無法弄清楚它是什么。

我已經注釋掉了違規代碼片段之后的所有內容。

源代碼:

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int intInput = 0;   /*Holds the target number (1000 in the challenge statement.)*/
    int n = 0;
    int count = 0;
    int intThreeMultiplier = 1;
    int intFiveMultiplier = 1;

    printf("Please enter a positive integer.\n");
    scanf("%d",intInput);

    for( ; (((intInput - n) % 3) != 0) ; n++)  
        {}

    /*for(; count <= ((intInput - n) / 3); count++)
        {
            if ((count % 5) != 0)
            {
                intThreeMultiplier += count;
            }
        }

    count = 0;
    for(n = 0 ; ((intInput - n) % 5) != 0 ; n++)
    {}

    for(; count <= ((intInput - n) / 5) ; count++)
    {
        intFiveMultiplier += count;
    }

    int sum = (3 * intThreeMultiplier) + (5 * intFiveMultiplier);
    printf("The sume of all multiples of 3 or 5 (inclusively) under %d is %d.",intInput, sum);*/
}

這是我第一次在 StackOverflow 上發帖,所以如果我違反了任何提問規則,我提前道歉,並感謝任何關於此的反饋。

此外,我非常願意接受有關編碼實踐的任何建議,或者我在使用 C 時犯的任何新手錯誤。

謝謝!

scanf("%d",intInput);

可能

scanf("%d", &intInput);  // note the ampersand

scanf需要存儲內容的變量的地址。 為什么scanf必須取operator的地址

僅用於調試,打印輸入以驗證輸入是否被正確接受,例如

printf("intInput = %d\n", intInput);

輸入intInput時需要的第一件事應該使用:

 scanf("%d", &intInput);    

因為scanf()需要作為指向變量的指針的參數。 您只需將 & 符號放在 int 之前即可完成此操作。

另外我認為你應該仔細檢查你的算法,因為你不止一次地總結了一些數字。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM