我用C语言写了一个平年闰年的问题,但是我把a定义成字符串了之后显示报错,但是当n是闰年的时候我打出来的是字,当n是平年的时候,输出的是数字零,所以我把a定义成字符串,请问为什么不对?
#include
#include
int temp(int n){
if((n%100!=0&&n%4==0)||n%400==0){
printf("闰年");
// system("pause")
}
else{
return 0;
}
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int n;
str a;
scanf("%d",&n);
a=temp(n);
printf("%s",a);
return 0;
}
① c语言无str类型
② 若返回的值为0,要被正确接收的话,要把变量a定义成int类型
printf和return的东西之间没关系。
C语言没有str这个类型
如果用a来存储字符串,可以把a定义成字符数组,str在c中不是代表字符串;
如果需要调用temp()函数参与一些判断的话,可以把temp()函数的if分支里面改为:return 1;
但程序如果只需要判断并打印输入的年份是平年还是闰年的话,可以把temp()函数里的else分支里面改为:printf("平年"); 来显示结果即可;
如果需要返回结果的字符串,那实现可能稍复杂点,可以在temp()函数里申请一块内存用于存储结果字符串,然后可以在结果返回指向结果字符串的指针;
现简单改为第二种情况,修改如下:
#include <stdio.h>
#include <stdlib.h>
void temp(int n){
if((n%100!=0&&n%4==0)||n%400==0){ // 闰年
printf("闰年");
// system("pause")
}
else{ // 平年
printf("平年");
}
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
int n;
//char a[10];
scanf("%d",&n);
temp(n);
// printf("%s",a);
return 0;
}