該程式只是應該通過從當前年份中減去他們的 dob 來計算用戶的年齡。當我運行程式時,它編譯成功,但我得到一個很長的數字,例如 -215863352。添加 if 和 else 條件只是為了測驗它們,我正在使用它們撰寫各種程式以確保我理解 c 中的語法。我想我錯過了一些簡單的東西,但無法弄清楚。
#include <stdio.h>
int main()
{
int year;
int cyear;
int age = cyear - year;
printf("Please enter the year you were born: \n");
scanf("%i", &year);
printf("Now enter the current year: \n");
scanf("%i", &cyear);
if (1 1 == 2){
printf("You must be %i", age);
}
else {
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}
uj5u.com熱心網友回復:
您正在計算從用戶那里獲取輸入之前的年齡。所以這個age變數存盤了一個垃圾值。
解決方案:
cyear使用scanf的輸入后,定位到用戶輸入后的年齡計算。下面給出了正確的代碼#include <stdio.h>
int main()
{
int year;
int cyear;
int age =0; //initialise with 0
printf("Please enter the year you were born: \n");
scanf("%i", &year);
printf("Now enter the current year: \n");
scanf("%i", &cyear);
age = cyear - year; //note the change here
if (1 1 == 2){
printf("You must be %i", age);
}
else {
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}
uj5u.com熱心網友回復:
enter code here
#include <stdio.h>
int main()
{
long long int year;
printf("Please enter the year you were born: \n");
scanf("%lld",&year);
long long int cyear;
printf("Now enter the current year: \n");
scanf("%lld",&cyear);
long long int age = cyear-year;
if (1){
printf("You must be %lld", age);
}
else { printf("Now enter the current year: \n");
scanf("%lld",&cyear);
printf("Cannot compute age, GOODBYE:\n");
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364031.html
下一篇:C中BST程式的功能之一的問題
