C語言項(xiàng)目全正整數(shù)后再計(jì)算的三種參考解答方法
【項(xiàng)目-全正整數(shù)后再計(jì)算】
輸入3個(gè)正整數(shù),其中任一數(shù)不是正整數(shù),程序輸出Invalid number!,然后結(jié)束運(yùn)行。當(dāng)?shù)?個(gè)數(shù)為奇數(shù)時(shí),計(jì)算后兩數(shù)之和,當(dāng)?shù)?個(gè)數(shù)為偶數(shù)時(shí),計(jì)算第2數(shù)減去第3數(shù)的差。無論哪種情形,當(dāng)結(jié)果超過10時(shí)按如下示例輸出,否則什么也不輸出。
示例 1:
Enter number 1: 2
Enter number 2: -7
Invalid number!
示例2:
Enter number 1: 17
Enter number 2: 3
Enter number 3: 6
示例3:
Enter number 1: 16
Enter number 2: 3
Enter number 3: 6
示例4:
Enter number 1: 11
Enter number 2: 4
Enter number 3: 22
Result: 26
示例5:
Enter number 1: 246
Enter number 2: 22
Enter number 3: 4
Result: 18
示例6:
Enter number 1: 246
Enter number 2: 4
Enter number 3: 22
解法1:嚴(yán)格按題目描述來,先輸入、再計(jì)算、最后輸出,直觀、清晰
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,y,z,a;
printf("Enter number 1:");
scanf("%d",&x);
if(x<=0)//第一個(gè)數(shù)字符號(hào)驗(yàn)證
{
printf("Invalid number.");
return 0;
}
printf("Enter number 2: ");
scanf("%d",&y);
if(y<=0)
{
printf("Invalid number.\n");
return 0;
}
printf("Enter the number 3: ");
scanf("%d",&z);
if(z<=0)
{
printf("Invalid number!\n");
return 0;
}
if(x%2!=0)//第一個(gè)數(shù)字是奇數(shù)的情況
{
a=y+z;
}
else//第一個(gè)數(shù)字是偶數(shù)情況
{
a=y-z;
}
if(a>10)
{
printf("Paul is the monkey king,He can lift %d jin!",a);
}
return 0;
}
解法2:三級(jí)選擇結(jié)構(gòu)的嵌套,優(yōu)先處理為正整數(shù)的情形
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,y,z,a;
printf("Enter number 1:");
scanf("%d",&x);
if(x>0)//第一個(gè)數(shù)字符號(hào)驗(yàn)證
{
printf("Enter number 2: ");
scanf("%d",&y);
if(y>0)
{
printf("Enter the number 3: ");
scanf("%d",&z);
if(z>0)
{
if(x%2!=0)
a=y+z;
else
a=y-z;
if(a>10)
printf("Result: %d\n",a);
}
else
printf("Invalid number.\n");
}
else
printf("Invalid number.\n");
}
else
printf("Invalid number.\n");
return 0;
}
解法3:用了一個(gè)技巧——變量ok初值為0,代表輸入數(shù)字為非正整數(shù),只有三數(shù)均為正整數(shù)后才賦值為1,這樣,在程序結(jié)束之前,可以依據(jù)ok判定是否三數(shù)全是正整數(shù)
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,y,z,a,ok=0;
printf("Enter number 1:");
scanf("%d",&x);
if(x>0)
{
printf("Enter number 2: ");
scanf("%d",&y);
if(y>0)
{
printf("Enter the number 3: ");
scanf("%d",&z);
if(z>0)
{
ok=1;
if(x%2!=0)
a=y+z;
else
a=y-z;
if(a>10)
printf("Result: %d\n",a);
}
}
}
if(ok==0) //若到此ok仍然為初值0,必定是某一個(gè)數(shù)非正整數(shù)了
printf("Invalid number.\n");
return 0;
}
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
相關(guān)文章
VS2019創(chuàng)建c++動(dòng)態(tài)鏈接庫dll與調(diào)用方法實(shí)踐
動(dòng)態(tài)鏈接庫是一個(gè)包含可由多個(gè)程序同時(shí)使用的代碼和數(shù)據(jù)的庫,本文主要介紹了VS2019創(chuàng)建c++動(dòng)態(tài)鏈接庫dll與調(diào)用方法,具有一定的參考價(jià)值,感興趣的可以了解一下2024-06-06
C/C++ 開發(fā)神器CLion使用入門超詳細(xì)教程
這篇文章主要介紹了C/C++ 開發(fā)神器CLion使用入門超詳細(xì)教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04

