2017-11-18 18 views
0

私はプログラミングが初めてで、パスワードが変更されない理由を理解しようとしています。私はピン= 1234移動しようとしました。メイン(void)では、何もしません。どのように私はこれを行うことができます任意のアイデア?パスワード変更C

#include <stdio.h> 
#include <string.h> 
void getPin(); 
void changePin(); 

int main(void) 
{ 
    getPin(); 
} 

void getPin() 
{ 
    int pin; 
    pin=1234; 
    int findPin; 
    printf("What is the pin?: "); 
    scanf("%d", &findPin); 
    int x=1; 
    while(x=1) 
    { 
    if (findPin == pin) 
     { 
     printf("\nAcces granted\n"); 
     changePin(); 
     break; 
     } 
    else 
     { 
     printf("\nAcces denied\n"); 
     printf("What is the pin?: "); 
     scanf("%d", &findPin); 
     x=1; 
     } 
    } 
} 

void changePin() 
{ 
    int pin; 
    int newPin; 
    printf("\nEnter new pin: "); 
    scanf("%d", &newPin); 
    pin = newPin; 
    printf("\nThe new pin is: %d\n", pin); 

    getPin(); 
} 

私はピンが変更された後、それは彼の初期値であるので、それはピン= 1234に再び行くことを推測しています。しかし、私は最初のピンを1234に持っていないようにそれをどのように変更できますか?

+0

あなたは、 '== '='との割り当てと'と平等のための比較の違いを知っていますか?あなたのループ 'while(x = 1)'のために私は不思議です。 –

+0

また、さまざまなスコープ(異なる機能のような)の異なる変数は、同じ名前を持っていても互いに無関係であることがわかりますか? –

+0

はい、パスワードを変更した後にgetPin()でpin = 1234と宣言した場合、値1234が再び取られます。値1234を変更しないようにするにはどうすればよいですか? –

答えて

0

新しいピンを保存できないのは、getPin()関数を入力するたびに1234を「ピン」変数に割り当てることです。 changePin()でパスワードを変更した後、getPin()を呼び出しています。

"ピン"をグローバル変数にして、あなたは良いです。

あなたのコードにはwhileステートメントに関する別の問題があります。 =は代入演算子です。あなたがしたいのはwhile(1)です。ここで

はコードです:ここでは

#include <stdio.h> 
#include <string.h> 
void getPin(); 
void changePin(); 

int pin = 1234; // Default pin 

int main(void) 
{ 
    getPin(); 
} 

void getPin() 
{ 
    int findPin; 
    printf("What is the pin?: "); 
    scanf("%d", &findPin); 
    while(1) 
    { 
    if (findPin == pin) 
     { 
     printf("\nAcces granted\n"); 
     changePin(); 
     break; 
     } 
    else 
     { 
     printf("\nAcces denied\n"); 
     printf("What is the pin?: "); 
     scanf("%d", &findPin); 
     } 
    } 
} 

void changePin() 
{ 
    int newPin; 
    printf("\nEnter new pin: "); 
    scanf("%d", &newPin); 
    pin = newPin; 
    printf("\nThe new pin is: %d\n", pin); 

    getPin(); 
} 

は、サンプル出力です:

What is the pin?: 1234 

Acces granted 

Enter new pin: 5555 

The new pin is: 5555 
What is the pin?: 1235 

Acces denied 
What is the pin?: 1234 

Acces denied 
What is the pin?: 55555 

Acces denied 
What is the pin?: 5555 

Acces granted 

Enter new pin: 3333 

The new pin is: 3333 
What is the pin?: 5555 

Acces denied 
What is the pin?: 1234 

Acces denied 
What is the pin?: 3333 

Acces granted 

は、この情報がお役に立てば幸いです。

バリス

関連する問題