请帮助我需要阻止传入的字母和负数 比如错误处理什么的 这是代码
{
printf("\nEnter number of Processes:");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Process ID %d :",i+1);
scanf("%d", &process[i]);
printf("\nEnter Process Time %d:",i+1);
scanf("%d",&ptime[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(ptime[i]>ptime[j])
{
temp = ptime[i];
ptime[i] = ptime[j];
ptime[j] = temp;
ptemp = process[i];
process[i] = process[j];
process[j] = ptemp;
}
}
}
wtime[0]=0;
for(i=1;i<n;i++)
{
wtime[i]=wtime[i-1]+ptime[i-1];
total=total+wtime[i];
}
avg=(float)total/n;
printf("\nProcess ID\t Process TIME\t Waiting TIME\n");
for(i=0;i<n;i++)
printf(" %d\t %d\t %d\n", process[i], ptime[i], wtime[i]);
printf("\nTotal Waiting Time: %d \nAverage Waiting Time: %f", total, avg);
提前致谢需要完成它嘿嘿嘿
最佳答案
简单方法:检查错误,如果有错误则终止。
// add #include <cstdlib> at the beginning of your code to use exit()
{
printf("\nEnter number of Processes:");
if(scanf("%d", &n)!=1 || n<0)exit(1);
for(i=0;i<n;i++)
{
printf("\nEnter Process ID %d :",i+1);
if(scanf("%d", &process[i])!=1 || process[i]<0)exit(1);
printf("\nEnter Process Time %d:",i+1);
if(scanf("%d",&ptime[i])!=1 || ptime[i]<0)exit(1);
}
更新:
要通过一个exit()
完成所有退出,使用标志是个好主意。
这样,更容易进行其他操作,例如打印错误消息。
// add #include <cstdlib> at the beginning of your code to use exit()
{
bool error_found = false;
printf("\nEnter number of Processes:");
if(scanf("%d", &n)!=1 || n<0)error_found = true;
else
{
for(i=0;i<n;i++)
{
printf("\nEnter Process ID %d :",i+1);
if(scanf("%d", &process[i])!=1 || process[i]<0){error_found = true; break;}
printf("\nEnter Process Time %d:",i+1);
if(scanf("%d",&ptime[i])!=1 || ptime[i]<0){error_found = true; break;}
}
}
if (error_found) {
// some error exists
puts("MUST NOT ALPHABET OR NEGATIVE NUMBER!");
exit(1);
}
关于c++ - 我如何处理字母和负数时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34114932/