理想国第七卷读后感:跪求高手提示一下这段C语言该怎么写?

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/05 07:39:16
叫用户输入不超过10位的数字,然后打出他输入的这个数字。还要能判断他输入的是正数还是负数。 。。。。刚开始学,万分感谢各位大虾。。提示一下也行。
一楼的大虾说的很好。。。。但如果用户输入的是其他东西而不是数字,该怎么办呢?还有,如果输完一次,还要用户选Y或N是否继续再输入。多谢阿,小弟刚才忘了问完了。。。。

算法思想: 把输入数据存为字符串,检查是否为数据,是则转换该字符串为数
据,然后输出其为正或负数.

#include <stdio.h>

int check(char str[]);
long ToNumber(char str[]);

main()
{
long num;
char str[11];
char c;

do
{
printf("Input the number:");
gets(str); /*输入数据以字符串保存*/
while(check(str) == 1) /*直到输入为数据为止*/
{
printf("It's not a number, input again.\n");
gets(str);
}

num = ToNumber(str); /*把字符串转换为数据*/
if(num > 0)
{
printf("It's a positive number.\n");
}
else if(num < 0)
{
printf("It's a negetive number.\n");
}
else
{
printf("It's zero.\n");
}
printf("Do you want to continue:(Y/N or y/n)");
c = getchar();
getchar();
}while(c == 'y' || c == 'Y');

getch();

}

int check(char str[])
{
int i;
for(i = 0; str[i] != '\0'; i++)
{ if(i == 0)
{
if(str[i] == '-')
continue;
}
if( !(str[i] >= '0' && str[i] <= '9') )
{
return 1;
}
}
return 0;
}

long ToNumber(char str[])
{
int i;
int neg = 1;
long temp = 0;

if(str[0] == '-')
{
neg = -1;
}
else
{
temp = str[0] - '0';
}
for(i = 1; str[i] != '\0'; i++)
{
temp = temp*10 + str[i] - '0';
}
return temp * neg;
}

如果要输入字符串就需要用到字符数组和字符串输入函数gets();
至于你说的需要判断Yes或No然后执行的就需要使用到循环拉
你可以参考一下我写的(按Q退出)
顺便问一下~你初学学到了循环和数组了吗?
#include<stdio.h>
#include<math.h>
void main()
{
unsigned n,d,p;
char temp;

while(temp!='Q' && temp!='q')
{
n=NULL;
printf("请输入您的QQ活跃天数:");
scanf("%d",&d);

if(d>=5&&d<=4294000000){
n=sqrt(4+d)-2;
printf("您目前的QQ等级是%d级\n",n);
p=(n+1)*(n+1)+4*(n+1)-d;
printf("升至%d级还需要%d天\n",n+1,p);
printf("\n");
}

else if(d>=0&&d<5)
printf("您目前的QQ等级是0级\n升至1级还需要%d天\n",5-d);

else
printf("无法理解\n");
scanf("%c",&temp);

}

}

测试过:
#include"stdio.h"
main()
{
float x;
char c='y';
do
{
do
{
if(c=='y'||c=='Y'){
printf("请输入十位数");

scanf("%f",&x);
}
}
while(x>=1000000000||x<=-10000000000);

if(x>0)printf("是正数");
else if(x<0)printf("是负数");
printf("是否继续?y or n:");
getch(c);

}
while(c=='y'||c=='Y');
}


可以运行,但是有点粗糙,不过基本符合你的要求

#include"stdio.h"
#include"math.h"
main()
{ float x;
char c='a';
label:
do { printf("\n 请输入一个不高于10位的数字:");
scanf("%f",&x);
} while(fabs(x)>9999999999);
if(x>0) printf("%.0f > 0",x);
else if(x<0) printf("%.0f < 0",x);
else printf("这个数是 0");
while(c!='y'||c!='Y'||c!='n'||c!='N')
{printf("\n 继续? y or n:");
c=getchar();
if(c=='y'||c=='Y') goto label;
else if(c=='n'||c=='N') exit(0);
}
}

这么简单!

#include"stdio.h"
main()
{
float a;
char t;
do
{
printf("请输入一个数");
scanf("%f",&a);
if(a<=9999999999)
{
prinf("%f\n",a);
if(a<0)
prinf("%f是负数",a)
}
else
printf(不能超过10位数);
scanf("%c",&t);
}while(t=='y'&&t=='Y');

中间还可以加个清除缓存的
要判断他只能输入数字不能有其他字符就麻烦多了