请帮助我需要阻止传入的字母和负数 像错误处理或其他东西 这是代码
{
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);
先谢谢你需要完成它hehehe
答案 0 :(得分:0)
简单方法:检查错误并在出现错误时终止。
listview.setAdapter(mydapter)
<强>更新强>
要完成所有退出adapter.notifyDataSetChanged()
,使用旗帜是一个好主意。
通过这种方式,可以更轻松地执行其他操作,例如打印错误消息。
// 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);
}
答案 1 :(得分:0)
尝试使用字符串类型获取输入,然后将字符串转换为您想要的结果。例如:
#include <string>
#include <iostream>
#include <sstream>
#include <exception>
using namespace std;
int main() {
int processed_input;
string input;
cin >> input;
stringstream ss(input);
try {
ss >> processed_input;
if(processed_input < 0) throw "Negative number";
} catch(exception &e) {
cout << "Error : non-numeric characters inputted";
} catch(const char* msg) {
cout << "Error : " << msg << " inputted";
}
return 0;
}