我是C編程新手(我通過vb.NET編程有一些非常基本的經驗),並且我正在嘗試爲Project Euler Problem#1編寫一個程序。 https://projecteuler.net/problem=1C程序在For循環崩潰
算法
挑戰需要程序員找到的低於1000 3或5(含)的所有倍數(I用於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);*/
}
這是我第一次張貼在計算器上,所以我提前道歉,如果我已經打破任何規則的提問,並希望對於這個任何反饋。
另外,我關於編碼習慣非常開放的任何建議,或任何新秀的錯誤我已經與C.
感謝訂做!
第一個循環不能夠崩潰,除非你有一個錯誤的編譯器生成錯誤的代碼。您是否曾嘗試在調試器中運行該程序以捕捉運行中的崩潰,然後找到實際發生的位置? –
爲什麼你評論了大部分代碼? – Barmar
爲什麼你需要2個循環?只需使用1循環,噹噹前數字是3或5的倍數時,將其添加到總數中。 – Barmar