有些事情已經在另一個答案中解釋過了,這只是一種不同的方法。
註釋原代碼:
/*Calculate Gotham's population*/
#include <stdio.h>
//Your population calculation depends on the year only, so you only need one argument
int get_population (int , double);
int main (void){
int t;
double population; //Can a not natural number of people exist? An int is better suited for this
printf("Enter a year after 1990 > ");
scanf("%d", &t);
//There is no need to cast the return of the function
//Also a cast to another type would be done by enclosing it with brackets
//Example: population = (int) get_population(t);
population = int get_population (t);
printf("Predicted Gotham City population for 2015 (in thousands):%f");
return 0;
}
int get_population (int t, double P){
double P = 52.966 + 2.184*t;
return P;
//The following code will not be executed, since the function has ended
printf("Predicted Gotham City population for 2015 (in thousands):%d");
}
以下是我怎麼想「修復」你的代碼:
/*Calculate Gotham's population*/
#include <stdio.h>
//Since the function only depends on the year, only 1 argument is needed
int get_population (int);
int main (void){
//Since a not natural number of people can't exist, using ints
int year, population;
printf("Enter a year after 1990 > ");
scanf("%d", &year);
//Calling the function that our code knows returns an int and assigning it to a variable
population = get_population (year);
//To use variables in a printf, you'll use the '%' followed by a description(%d for (decimal) int, %c for char, %s for strings,...)
//And add those variables, in the right order, at the end
printf("Predicted Gotham City population for %d (in thousands):%d", year, population);
return 0;
}
//Since you only do the same thing every time, you can just return the calculation
int get_population (int year){
return (52.966 + 2.184*year);
}
如果你理解了變化,也許嘗試加入一些故障安全測試,也許輸出如果輸入年份是1990年<
人口另一個文本= INT get_population(T); <=這裏不需要「int」,也可以將返回int的函數的結果賦值給double。 –
我很漂亮,這不會編譯。這是行中的'int'是什麼?population = int get_population(t);'?另外函數get_population()中的printf不可訪問。並且你的函數參數像局部變量('P')一樣。 – kaetzacoatl
不是int函數類型 – Sam