2015-11-22 54 views
1

我需要編寫一個程序,計算3^2 + 6^2 + 9^2 + ... +(3×N)^ 2,給定一個給定整數N的用戶。程序會提示用戶輸入一個整數,是小於20.該方案應經過3個錯誤chances.This站是我的代碼:我的程序忽略'while'循環

#include <stdio.h> 
int main(){ 
     int n,x,i ; 
     float p; 
     printf("Hey give me a positive integer number smaller than 20 \n "); 
     scanf("%d" ,&n); 
     x=3; 
     p=0; 
     while ((n<=0) && (n>=20)){ 
       printf("wrong input %d chances left \n" ,x); 
       x--; 
       if (x==0) return 0; 
       scanf("%d" , &n); 
     } 
     for (i=0; i<=n; i++){ 
       p= (3*i)* (3*i) + p ; 
     } 
     printf("Yeah.. thats the result bro %f \n" , p); 
     return 0; 
} 

我想不通爲什麼它不會進入while循環。請幫忙。

回答

5
while ((n<=0) && (n>=20)){ 

看到在這個循環條件,你知道的任何數量的爲小於或等於0,比20更大? 。

此循環只適用於這樣的數字,因爲您使用了&&運算符,只有當兩個條件都滿足時纔會成立(因此您的循環不會迭代)。

使用||運營商的環 -

while ((n<=0) || (n>=20)){